如何检索 Mongo DB 中数组中存在的所有匹配元素?

Sac*_*ach 3 mongodb mongodb-java mongodb-query spring-data-mongodb

我有如下所示的文件:

{
  name: "testing",
  place:"London",
  documents: [ 
                        {   
                            x:1,
                            y:2,
                        },
                        {
                            x:1,
                            y:3,
                        },
                        {
                            x:4,
                            y:3,
                        }
            ]
    }
Run Code Online (Sandbox Code Playgroud)

我想检索所有匹配的文档,即我想要以下格式的 o/p:

{
    name: "testing",
    place:"London",
    documents: [ 
                        {   
                            x:1,
                            y:2,
                        },
                        {
                            x:1,
                            y:3,
                        }

            ]
    }
Run Code Online (Sandbox Code Playgroud)

我尝试过的是:

db.test.find({"documents.x": 1},{_id: 0, documents: {$elemMatch: {x: 1}}});
Run Code Online (Sandbox Code Playgroud)

但是,它只提供第一个条目。

小智 5

正如JohnnyHK所说,MongoDB中的答案:选择子集合的匹配元素很好地解释了它。

在您的情况下,聚合如下所示:

(注意:第一次匹配不是绝对必要的,但它在性能(可以使用索引)和内存使用(有限集上的 $unwind )方面有所帮助

> db.xx.aggregate([
...      // find the relevant documents in the collection
...      // uses index, if defined on documents.x
...      { $match: { documents: { $elemMatch: { "x": 1 } } } }, 
...      // flatten array documennts
...      { $unwind : "$documents" },
...      // match for elements, "documents" is no longer an array
...      { $match: { "documents.x" : 1 } },
...      // re-create documents array
...      { $group : { _id : "$_id", documents : { $addToSet : "$documents" } }}
... ]);
{
    "result" : [
        {
            "_id" : ObjectId("515e2e6657a0887a97cc8d1a"),
            "documents" : [
                {
                    "x" : 1,
                    "y" : 3
                },
                {
                    "x" : 1,
                    "y" : 2
                }
            ]
        }
    ],
    "ok" : 1
}
Run Code Online (Sandbox Code Playgroud)

有关aggregation() 的更多信息,请参阅http://docs.mongodb.org/manual/applications/aggregation/