基于月份和日期的MongoDB查询

时间:2019-01-09 09:28:21

标签: node.js database mongodb mongoose

所以,我的数据库中有这些数据,

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "from": "1970-01-01",
    "to": "1970-01-05"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "from": "2017-04-18",
    "to": "2017-04-23"
  },
  {
    "_id": ObjectId("5a934e000102030405000002"),
    "from": "2018-01-29",
    "to": "2018-01-30"
  },
  {
    "_id": ObjectId("5a934e000102030405000003"),
    "from": "2018-01-02",
    "to": "2018-01-08"
  }
]

是否有可能使年( 2018 )和月( 01 )通过,然后从所有数据中获得匹配数据?像这里一样,我从集合中获得了最后两个文档。

我尝试了 $ elemMatch:查询,但没有得到预期的结果。

2 个答案:

答案 0 :(得分:2)

您也可以尝试以下操作:

db.collection.find( 
    {"from": {"$gte": new Date(2018, 0, 1), "$lt": new Date(2018, 1, 1)}}
)

另外,请记住,在Date()函数中,month参数从0开始计数,而不是1。

更新: MongoDB V3.4

db.collection.aggregate([
      {$project: {  "month" : {$month: '$date'}, "year" : {$year: '$date'}}},
      {$match: { month: 1, year: 2018}}
    ]);

答案 1 :(得分:1)

您可以使用正则表达式。以下示例使用猫鼬:

model.find({
  from: {
     $regex: new RegExp('2018-01-', ''),
  },
});

model.find({
  from: {
     $regex: /2018-01-/,
  },
});

使用mongoshell格式:

db.collection.find({
  from: {
    $regex: "2018-01"
  }
})

https://mongoplayground.net/p/udRts-zp2D9

相关问题