mongodb - 如何检索Mongodb中数组中存在的所有匹配元素?

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

我有如下所示的文件:

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

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

最佳答案

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

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

关于mongodb - 如何检索Mongodb中数组中存在的所有匹配元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15429243/

相关文章:

mongodb 计数并删除重复值

java - com.mongodb.DB.authenticate(String,String) 是在内存中进行身份验证还是调用 mongo db?

java - 在 SpringMVC 应用程序中初始化 MongoDB 存储库时出错

java - 如何查找两个 LocalDateTime 之间插入的所有 MongoDB 文档

javascript - 使用 HTML 显示 MongoDB 文档

node.js - 填充时连接字符串

MongoDB 平均返回 NULL

mongodb - $sum 有多个条件

mongodb - 如何在文档字段 MongoDB 中找到相似性?

java - Java 中的 MongoDB 文档更新 : coding error or driver bug?