MongoDB + Node.js:如何查询ISODate字段?

74

我正在使用nodejs和node-mongodb-native驱动程序(http://mongodb.github.io/node-mongodb-native/)。

我有一些文档,其中一个日期属性以ISODate类型存储。

通过nodejs,我正在使用以下查询:

db.collection("log").find({
    localHitDate: { 
            '$gte': '2013-12-12T16:00:00.000Z',
            '$lt': '2013-12-12T18:00:00.000Z' 
    }
})

它不返回任何东西。为了使其工作,我需要执行以下操作:

db.collection("log").find({
    localHitDate: {
            '$gte': ISODate('2013-12-12T16:00:00.000Z'),
            '$lt': ISODate('2013-12-12T18:00:00.000Z')
    }
})

但是ISODate在我的Node.js代码中无法识别。

那么我该如何通过我的Node.js程序对Mongo日期字段进行查询?

谢谢

4个回答

103
您可以在node.js中使用new Date('2013-12-12T16:00:00.000Z'); new是必需的,因为Date()已经用于返回日期字符串。 ISODate是mongodb中的概念,您可以在mongodb控制台中使用它,但对于不同的编程语言,可能会有所不同。

我真的很难搞定这个问题... 我似乎无法将UTC ISO日期存储在Mongo中,以拯救我的生命... https://dev59.com/L4Xca4cB1Zd3GeqPDRhw - Cmag
谢谢你的回答。省了很多时间。 - Shyamali
1
这是指12月还是12日? - Guerlando OCs

10

你可以使用这个,对我来说完美地起作用了。

//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');

//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;

// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost/klevin';

// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {

  if (err) {
    console.log('Unable to connect to the mongoDB server. Error:', err);
  } else {
    //HURRAY!! We are connected. :)
    console.log('Connection established to', url);


    // Get the documents collection
    var collection = db.collection('frames');

    //We have a cursor now with our find criteria
    var cursor = collection.find({
      tv: 'tematv', 
      date_created: {"$gte": new Date("2015-10-01T00:00:00.000Z") , "$lt": new Date("2017-03-13T16:17:36.470Z") }});

    //We need to sort by age descending
    cursor.sort({_id: -1});

    //Limit to max 10 records
    cursor.limit(50);

    //Skip specified records. 0 for skipping 0 records.
    cursor.skip(0);


    //Lets iterate on the result
    cursor.each(function (err, doc) {

      if (err) {

        console.log(err);

      } else {

        console.log('Fetched:', doc);

        if(doc !== null){ 

        }

      }
    });


  }

});

0

我们需要使用 new Date() 来获取数据是最佳选择。

db.getCollection('orders').aggregate([
  {
    '$match': {
      $and: [
        {
          status: 'UNASSIGNED'
        },
        {
          plannedDeliveryDate: {
            '$eq': new Date('2017-10-09')
          }
        }
      ]
    }
  },
  {
    $lookup: {
      from: "servicelocations",
      localField: "serviceLocationId",
      foreignField: "serviceLocationId",
      as: "locations"
    }
  },
  {
    $unwind: "$locations"
  },
  {
    "$project": {
      "accountId": 1,
      "orderId": 1,
      "serviceLocationId": 1,
      "orderDate": 1,
      "description": 1,
      "serviceType": 1,
      "orderSource": 1,
      "takenBy": 1,
      "plannedDeliveryDate": 1,
      "plannedDeliveryTime": 1,
      "actualDeliveryDate": 1,
      "actualDeliveryTime": 1,
      "deliveredBy": 1,
      "size1": 1,
      "size2": 1,
      "size3": 1,
      "jobPriority": 1,
      "cancelReason": 1,
      "cancelDate": 1,
      "cancelBy": 1,
      "reasonCode": 1,
      "reasonText": 1,
      "status": 1,
      "lineItems": 1,
      "locations": {
        "lng": "$locations.location.lng",
        "lat": "$locations.location.lat"
      }
    }
  }
])

0

你可以查看我在其他问题中提供的答案。

他们使用$gte:“yyyy-mm-dd”,$lte:“yyyy-mm-dd”来替换$eq。

NodeJS MongoDB:查询ISO日期

希望这能帮助你或其他人!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接