如何在MongoDB中返回数组匹配条件的元素

如何在MongoDB中返回数组匹配条件的元素,mongodb,Mongodb,我是mongodb的新手,我仍在努力解决问题,所以如果我的问题太简单或在其他地方得到了回答,请原谅我 我有一个像下面这样的收藏 [ {"_id":1, "data" :[{"a":1,"b":2},{"a":1,"b":3},{"a":2,"b":3},{"a":4,"b":1}] }, {"_id":2, "data" :[{"a":3,"b":2},{"a":2,"b":4},{"a":5,"b":3},{"a":7,"b":1}] } ] 如何编写一个查询,在第一个文档的数据数组中查找并

我是mongodb的新手,我仍在努力解决问题,所以如果我的问题太简单或在其他地方得到了回答,请原谅我

我有一个像下面这样的收藏

[
{"_id":1,
"data" :[{"a":1,"b":2},{"a":1,"b":3},{"a":2,"b":3},{"a":4,"b":1}]
},
{"_id":2,
"data" :[{"a":3,"b":2},{"a":2,"b":4},{"a":5,"b":3},{"a":7,"b":1}]
}
]
如何编写一个查询,在第一个文档的数据数组中查找并返回“a”等于1的所有元素

这是预期的输出:

[{"a":1,"b":2},{"a":1,"b":3}]
这是我目前的尝试

db.myCollection.find({_id:1},{data: {$elemMatch: {a : 1}}})
但这给了我

{"_id": 1, "data":
[{"a":1,"b":2},{"a":1,"b":3}]
}
除了“数据”中的结果之外,我不需要或想要其他任何东西

有人能帮我一下吗


我还希望有任何指针可以在文档中的数组中筛选与单个文档上更一般条件匹配的元素(例如,在上面的示例中,查找a+b<5、a>b、a>1和b>2、a>3或b的文档,您几乎拥有了所有内容,您只是忘记了末尾的投影:

db.myCollection.find({_id:1},{data: {$elemMatch: {a : 1}}}, {_id: 0, data: 1})

$filter
是筛选文档内部数组的通用方法。扩展输入集以提供更多的上下文和种类:

var r =
[
 {
     "_id": 0,
     "other":6,
     "data" :[{"a":1,"b":2,"c":"X"},
              {"a":1,"b":3,"c":"Y"},
              {"a":2,"b":3,"c":"Q"},
              {"a":4,"b":1,"c":"Z"}]
 },
 {
     "_id": 1,
     "other":7,
     "data" :[{"a":1,"b":2,"c":"A"},
              {"a":1,"b":3,"c":"B"},
              {"a":7,"b":7,"c":"C"},
              {"a":1,"b":8,"c":"D"}]
 }
];
db.foo.insert(r);
然后,这两个管道演示了
$filter
的多功能性:

c = db.foo.aggregate([
{$project: {_id:false,
            // Notice input is $data and output project is data; this                     
            // means overwrite the old data array with the filtered array.                 
            // Also:  The double dollar is how we reference the "as"                      
            // variable.  Single dollar variables refer to the fields                     
            // of the incoming doc; we show how to use $other in this                     
            // example.   $other remains constant for the doc as $filter
            // marches down the $data array:                                                                 
            data: {$filter: {
                input: "$data",
                as: "z",
                cond: { $lt: [ {$add:["$$z.a","$$z.b"]} , "$other" ]}
            }}
    }}
                       ]);


c = db.foo.aggregate([
{$project: {_id:true,
            data: {$filter: {
                input: "$data",
                as: "z",
                cond: { $or: [ {$gt:["$$z.a",3]}, {$lt:["$$z.b",7]} ] }
            }}
    }}
                       ]);