您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用MongoDB过滤子文档中的数组

如何使用MongoDB过滤子文档中的数组

使用aggregate是正确的方法,但在应用数组之前需要先$unwindlist数组进行$match过滤,以便可以过滤单个元素,然后用于$group将其放回原处:

db.test.aggregate([
    { $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
    { $unwind: '$list'},
    { $match: {'list.a': {$gt: 3}}},
    { $group: {_id: '$_id', list: {$push: '$list.a'}}}
])

输出

{
  "result": [
    {
      "_id": ObjectId("512e28984815cbfcb21646a7"),
      "list": [
        4,
        5
      ]
    }
  ],
  "ok": 1
}

MongoDB 3.2更新

从3.2发行版开始,您可以使用新的$filter聚合运算符来提高效率,只需list在$project:中包括所需的元素即可:

db.test.aggregate([
    { $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
    { $project: {
        list: {$filter: {
            input: '$list',
            as: 'item',
            cond: {$gt: ['$$item.a', 3]}
        }}
    }}
])
mongodb 2022/1/1 18:25:30 有414人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶