我在子文档中有这样的数组

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

Can I filter subdocument for a > 3

我的预期结果如下

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

我try 使用$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
        }
    ]
}

我可以在数组中筛选元素以获得预期结果吗?

推荐答案

使用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 Update

从3.2版开始,您可以使用新的$filter聚合操作符来更高效地完成这项工作,只需在$project:

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

Mongodb相关问答推荐

如何$匹配在命令列表中查找确切的命令

MongoDB与合并对象聚合

MongoDB DB参考返回null值

Mongoose 聚合和多级组

如何在查找 foreignField 中使用通配符?

如何在 go mongo-driver 中为 options.FindOne() 设置限制

在亚马逊 EC2 上托管 nodeJS/mongoose Web 应用程序

mongodb:多键索引 struct ?

MongoDB 更改流副本集限制

如果 mongoDB 服务器正在运行,如何从驱动程序判断

Mongo查找对象内最长数组的查询

如何在 MongoDb 中使用杰克逊将日期字段存储为 ISODate()

单个模式数组中的多个模式引用 - mongoose

如何在 MongoDB Map-reduce 映射函数中使用变量

将 MongoCursor from ->find() 转换为数组

在 mongodb 中插入当前日期时间

MongoDB:查询和检索嵌入式数组中的对象?

查询不等于 null 或空的地方

MongoDB备份计划

即使重新安装后,Mongo 仍在等待 27017