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

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

问题描述

我有一个集合 Notebook,其中嵌入了名为 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

成为查询.谁能帮帮我.

be the query. Can anyone help me.

推荐答案

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

我不相信您要问的是可能的,至少可能没有一些 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天全站免登陆