如何检索Mongo DB中数组中存在的所有匹配元素? [英] How to retrieve all matching elements present inside array in Mongo DB?

查看:87
本文介绍了如何检索Mongo DB中数组中存在的所有匹配元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档如下所示:

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

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

I want to retrieve all matching documents i.e. I want o/p in below format:

{
    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}}});

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

But, it gives first entry only.

推荐答案

正如JohnnyHK所说,答案

As JohnnyHK said, the answer in MongoDB: select matched elements of subcollection explains it well.

在您的情况下,汇总看起来像这样:

In your case, the aggregate would look like this:

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

(note: the first match is not strictly necessary, but it helps in regards of performance (can use index) and memory usage ($unwind on a limited set)

> 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
}

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

For more information about aggregate(), see http://docs.mongodb.org/manual/applications/aggregation/

这篇关于如何检索Mongo DB中数组中存在的所有匹配元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆