且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 MongoDB 集合中获取特定的嵌入文档?

更新时间:2023-02-14 09:54:48

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

我不相信您要问的是可能的,至少可能没有一些 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.