如何在mongodb中选择子文档数组的一部分?

时间:2016-12-08 14:55:04

标签: mongodb mongodb-query

所以我在下面有这个数据结构;它基本上是为机构设定的事件日历。

{
    "_id" : ObjectId("58485e8b630c3106ba4af558"),
    "institutionId" : "6z66TRkvmEpCkLsKH",
    "events" : [ 
        {
            "name" : "Christmas Day",
            "date" : ISODate("2016-12-25T21:21:11.874Z"),
            "holiday" : true
        }, 
        {
            "name" : "Independence Day",
            "date" : ISODate("2016-08-04T21:21:11.874Z"),
            "holiday" : true
        }, 
        {
            "name" : "My Birthday",
            "date" : ISODate("2016-06-20T21:21:11.874Z"),
            "holiday" : false
        }
    ],
    "createdAt" : ISODate("2016-12-07T19:10:03.351Z")
}

如何获得假期的阵列? (假期=真)

[ 
  {
      "name" : "Christmas Day",
      "date" : ISODate("2016-12-25T21:21:11.874Z"),
      "holiday" : true
  }, 
  {
      "name" : "Independence Day",
      "date" : ISODate("2016-08-04T21:21:11.874Z"),
      "holiday" : true
  }
]

这是为机构存储日历事件的正确方法,还是每个文档都有一个事件?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以非常轻松地使用聚合执行此操作,也可以在投影中使用$ elemMatch进行此操作。

db.collection.aggregate([
    // Create a separate document for each element in your array
    { $unwind: '$events' },
    // Match only on the holidays
    { $match: { 'events.holiday': true } },
    // Regroup to form the array with only the matching holidays
    { $group: { _id: null, holidays: { $addToSet: '$events' }  } },
    // Return only the holidays array, and not the _id
    { $project: { _id: 0, holidays: 1 } }
]);

返回:

{ 
    "holidays" : [ 
        { 
            "name" : "Independence Day", 
            "date" : ISODate("2016-08-04T21:21:11.874Z"), 
            "holiday" : true 
        }, 
        { 
            "name" : "Christmas Day", 
            "date" : ISODate("2016-12-25T21:21:11.874Z"), 
            "holiday" : true 
        } 
    ] 
}