如何在MongoDB集合中获取特定的嵌入式文档? [英] How to get a specific embedded document inside a MongoDB collection?

查看:54
本文介绍了如何在MongoDB集合中获取特定的嵌入式文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个笔记本集合,其中嵌入了名为Notes的数组文档.样本

I have a collection Notebook which has embedded array document called Notes. The sample

文档如下所示.

{
"_id" : ObjectId("4f7ee46e08403d063ab0b4f9"),
"name" : "MongoDB",
"notes" : [
            {
              "title" : "Hello MongoDB",
              "content" : "Hello MongoDB"
            },
            {
              "title" : "ReplicaSet MongoDB",
              "content" : "ReplicaSet MongoDB"
            }
         ]
}

我只想查找标题为"Hello MongoDB"的音符.我没有得到应有的东西

I want to find out only note which has title "Hello MongoDB". I am not getting what should

是查询.谁能帮我.

推荐答案

过时的答案:请参见其他答案.

我不相信您的要求是可能的,至少可能没有一些map-reduce?

I don't believe what you are asking is possible, at least without some map-reduce maybe?

请参阅此处:在MongoDB中过滤嵌入式文档

该答案建议您更改架构,以更好地适应您想要使用数据的方式.

That answer suggests you change your schema, to better suit how you'd like to work with the data.

您可以使用点符号"或$ elemMatch来获取具有匹配的注释标题"的正确文档...

You can use a either "dot notation" or $elemMatch to get back the correct, document that has the matching "note title" ...

> db.collection.find({ "notes.title" : "Hello MongoDB"}, { "notes.title" : 1"});

或...

> db.collection.find({ "notes" : { "$elemMatch" : { "title" : "Hello MongoDB"} }});

但是您将获得整个数组,而不仅仅是导致匹配的数组元素.

But you will get back the whole array, not just the array element that caused the match.

此外,要考虑一下...在当前设置下,很难对数组中的项目执行任何操作.

Also, something to think about ... with your current setup it woud be hard to do any operations on the items in the array.

如果您不更改架构(正如链接所暗示的那样)...我会考虑向数组中的每个元素添加"id",以便您可以根据需要轻松地执行删除操作.

If you don't change your schema (as the answer linked to suggests) ... I would consider adding "ids" to each element in the array so you can do things like delete it easily if needed.

这篇关于如何在MongoDB集合中获取特定的嵌入式文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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