【问题标题】:How to retrieve all matching elements present inside array in Mongo DB?如何检索MongoDB中数组中存在的所有匹配元素?
【发布时间】:2013-03-03 23:32:27
【问题描述】:

我的文件如下所示:

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

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

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

            ]
    }

我试过的是:

db.test.find({"documents.x": 1},{_id: 0, documents: {$elemMatch: {x: 1}}});

但是,它只给出第一个条目。

【问题讨论】:

标签: mongodb mongodb-query mongodb-java spring-data-mongodb


【解决方案1】:

正如 JohnnyHK 所说,MongoDB: select matched elements of subcollection 中的答案很好地说明了这一点。

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

(注意:第一个匹配不是绝对必要的,但它有助于提高性能(可以使用索引)和内存使用($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
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多