English 中文(简体)
MongoDB - Return query based ondate
原标题:MongoDB - return query based on date

我在蒙戈布有这样的数据。

{ 
    "latitude" : "", 
    "longitude" : "", 
    "course" : "", 
    "battery" : "0", 
    "imei" : "0", 
    "altitude" : "F:3.82V", 
    "mcc" : "07", 
    "mnc" : "007B", 
    "lac" : "2A83", 
    "_id" : ObjectId("4f0eb2c406ab6a9d4d000003"), 
    "createdAt" : ISODate("2012-01-12T20:15:31Z") 
}

我如何问:<代码>db.gpsdatas.find({创建At:?)? 什么?} ,以便从db中把上述数据带回我?

最佳回答

例如,你可能想提出一系列问题,例如,在规定日期之后产生的所有项目:

db.gpsdatas.find({"createdAt" : { $gte : new ISODate("2012-01-12T20:15:31Z") }});

I m using $gte (greater than or equals), because this is often used for date-only queries, where the time component is 00:00:00.

如果你真的想要找到一个日期,这个日期等于另一个日期,那么该日子就是这样。

db.gpsdatas.find({"createdAt" : new ISODate("2012-01-12T20:15:31Z") });
问题回答

在Mongo v3.2.3中,使用Node v0.12.7和v4.4.4实施类似情况,并使用:

{ $gte: new Date(dateVar).toISOString() }

I m穿过ISODate(例如2016-04-22T00:00Z)和用于与ISOString功能或没有该功能的 que门。 但是,在用美元提款时,它就象标准化组织的职能一样!

If you want to get items anywhere on that date you need to compare two dates

你们可以创造出两个日期,如头一个日期,即从当天开始,到当天结束。

var startDate = new Date(); // this is the starting date that looks like ISODate("2014-10-03T04:00:00.188Z")

startDate.setSeconds(0);
startDate.setHours(0);
startDate.setMinutes(0);

var dateMidnight = new Date(startDate);
dateMidnight.setHours(23);
dateMidnight.setMinutes(59);
dateMidnight.setSeconds(59);

### MONGO QUERY

var query = {
        inserted_at: {
                    $gt:morning,
                    $lt:dateScrapedMidnight
        }
};

//MORNING: Sun Oct 12 2014 00:00:00 GMT-0400 (EDT)
//MIDNIGHT: Sun Oct 12 2014 23:59:59 GMT-0400 (EDT)

If you want to get all new things in the past 5 minutes you would have to do some calculations, but its not hard...

第一,就你想要匹配的财产编制一个指数(包括降水方向1和降水指标1)。

db.things.createIndex({ createdAt: -1 }) // descending order on .createdAt

然后询问过去5分钟的文件(60秒* 5分钟)。

db.things.find({
        createdAt: {
            $gte: new Date(new Date().getTime()-60*5*1000).toISOString()
         }
     })
     .count()

<代码>新日期(新日期(新日期)-60*5*1000)。

第一,我们计算“5分钟前”:

  1. new Date().getTime() gives us current time in milliseconds
  2. We want to subtract 5 minutes (in ms) from that: 5*60*1000 -- I just multiply by 60 seconds so its easy to change. I can just change 5 to 120 if I want 2 hours (120 minutes).
  3. new Date().getTime()-60*5*1000 gives us 1484383878676 (5 minutes ago in ms)

现在,我们需要将这一数据输入<代码>新日期()的构造者,以获得MongoDB时序所需的ISO扼制格式。

  1. { $gte: new Date(resultFromAbove).toISOString() } (mongodb .find() query)
  2. Since we can t have variables we do it all in one shot: new Date(new Date().getTime()-60*5*1000)
  3. ...then convert to ISO string: .toISOString()
  4. new Date(new Date().getTime()-60*5*1000).toISOString() gives us 2017-01-14T08:53:17.586Z

当然,如果你重新使用权宜之计的驱动力,这比变数小得多,但是,这在通常用于检查情况的省会中进行。

www.un.org/Depts/DGACM/index_spanish.htm 具体日期:

db.getCollection( CollectionName ).find({"DepartureDate" : new ISODate("2019-06-21T00:00:00.000Z")})

www.un.org/Depts/DGACM/index_spanish.htm Find with greater gte or Little lt :

db.getCollection( CollectionName ).find({"DepartureDate" : { $gte : new ISODate("2019-06-11T00:00:00.000Z") }})

www.un.org/Depts/DGACM/index_spanish.htm 范围:

db.getCollection( CollectionName ).find({ 
    "DepartureDate": { 
        $lt: new Date(), 
        $gte: new Date(new Date().setDate(new Date().getDate()-15))
      } 
    })

也可以尝试:

{
    "dateProp": { $gt: new Date( 06/15/2016 ).getTime() }
}

如果你使用Mongoose,

try {
  const data = await GPSDatas.aggregate([
    {
      $match: { createdAt : { $gt: new Date() }
    },
    {
      $sort: { createdAt: 1 }
    }
  ])
  console.log(data)

} catch(error) {
    console.log(error)
}

在个人方面,我更希望避免像时间一样使用客户方的javascript处理/第三方图书馆,以避免在客户一方和服务器方面进行时间区处理不一致。

  1. range-based query
db.collection.find({
  "createdAt": {
    $gte: ISODate("2012-01-12T00:00:00Z"),
    $lt: ISODate("2012-01-13T00:00:00Z")
  }
})
  1. constructed date range with $dateFromParts
db.collection.find({
  $expr: {
    $gte: [
      "$createdAt",
      {
        "$dateFromParts": {
          "year": 2012,
          "month": 1,
          "day": 12
        }
      }
    ]
  }
})
  1. get range with date difference(example is 15 years before current date)
db.collection.find({
  $expr: {
    $gte: [
      "$createdAt",
      {
        "$dateSubtract": {
          "startDate": "$$NOW",
          "unit": "year",
          "amount": 15
        }
      }
    ]
  }
})

如果你使用阳性聚聚物,那么就在此是:

  1. Here i am converting date which is dd/mm/yyyy to ISO Date (bcoz date is stored in ISO Date format in db)

const dateToIso=(from, to)=>{
    return {
        fromIsoDate: moment(from,"DD/MM/YYYY").toISOString(),
        toIsoDate: moment(to,"DD/MM/YYYY").add(1, days ).toISOString()
    }
}
  1. finally these values using mongodb aggregation:

{
                $match:{
                    $and:[
                        {
                            createdAt:{
                                $lte: new Date(toIsoDate)
                            }
                        },
                        {
                            createdAt:{
                                $gte: new Date(fromIsoDate)
                            }
                        },
                        
                    ]
                }
            },




相关问题
Access DB Ref MongoDB

Whats the best way to access/query a DB Ref: UPDATE: users: name, groupref : {$ref:"groups",$id:"ObjectId ..." } } groups: name, topic, country,...,.. Assumption is that user belongs to only one ...

MongoDB nested sets

What re the best practices to store nested sets (like trees of comments) in MongoDB? I mean, every comment can have a parent comment and children-comments (answers). Storing them like this: { ...

MongoMapper and migrations

I m building a Rails application using MongoDB as the back-end and MongoMapper as the ORM tool. Suppose in version 1, I define the following model: class SomeModel include MongoMapper::Document ...

MongoDB takes long for indexing

I have the following setup: Mac Pro with 2 GB of RAM (yes, not that much) MongoDB 1.1.3 64-bit 8 million entries in a single collection index for one field (integer) wanted Calling .ensureIndex(...) ...

Storing and accessing large amounts of data

My application creates pieces of data that, in xml, would look like this: <resource url="someurl"> <term> <name>somename</name> <frequency>somenumber</...

热门标签