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

34 浏览
0 Comments

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

这个问题在这里已经有答案了:
在 MongoDB 集合中检索仅查询的对象数组中的元素

社区审查了是否重新开放这个问题6个月前并将其保持关闭状态:

原始关闭原因未得到解决

我有一个子文档中的数组如下所示

{
    "_id" : ObjectId("512e28984815cbfcb21646a7"),
    "list" : [
        {
            "a" : 1
        },
        {
            "a" : 2
        },
        {
            "a" : 3
        },
        {
            "a" : 4
        },
        {
            "a" : 5
        }
    ]
}

我可以为 a > 3 过滤子文档吗?

我期望的结果如下

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

我尝试使用 $elemMatch 但返回数组中的第一个匹配元素

我的查询:

db.test.find( { _id" : ObjectId("512e28984815cbfcb21646a7") }, { 
    list: { 
        $elemMatch: 
            { a: { $gt:3 } 
            } 
    } 
} )

结果返回数组中的一个元素

{ "_id" : ObjectId("512e28984815cbfcb21646a7"), "list" : [ { "a" : 4 } ] }

我尝试使用 $match 和聚合但不起作用

db.test.aggregate({$match:{_id:ObjectId("512e28984815cbfcb21646a7"), 'list.a':{$gte:5}  }})

它返回数组中的所有元素

{
    "_id" : ObjectId("512e28984815cbfcb21646a7"),
    "list" : [
        {
            "a" : 1
        },
        {
            "a" : 2
        },
        {
            "a" : 3
        },
        {
            "a" : 4
        },
        {
            "a" : 5
        }
    ]
}

我可以过滤数组中的元素以获得期望结果吗?

admin 更改状态以发布 2023年5月24日
0
0 Comments

以上的解决方案在需要多个匹配子文档时效果最佳。\n如果需要单个匹配的子文档作为输出,$elemMatch也非常有用。\n

db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1})

\n结果:\n

{
  "_id": ObjectId("..."),
  "list": [{a: 1}]
}

0
0 Comments

使用 aggregate 是正确的方法,但在应用 $match 之前需要对 list 数组进行$unwind ,以便过滤单个元素,然后使用$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聚合运算符,通过在$project期间仅包括您想要的list元素来更有效地执行此操作:

db.test.aggregate([
    { $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
    { $project: {
        list: {$filter: {
            input: '$list',
            as: 'item',
            cond: {$gt: ['$$item.a', 3]}
        }}
    }}
])

$and:
获取0-5之间的数据:

cond: { 
    $and: [
        { $gt: [ "$$item.a", 0 ] },
        { $lt: [ "$$item.a", 5) ] }
]}

0