如何从所有文档中仅返回数组的嵌套文档 [英] How to return just the nested documents of an array from all documents
问题描述
我有一个关于查询嵌套文档的问题.我试图搜索,但没有任何答案回答我,或者我可能忽略了它.我有这样的结构:
I have a question about querying nested documents. I tried to search but nothing answered my question or I am maybe overlooking it. I have structure like this:
{
"_id" : ObjectId("592aa441e0f8de09b0912fe9"),
"name" : "Patrick Rothfuss",
"books" : [
{
"title" : "Name of the wind",
"pages" : 400,
"_id" : ObjectId("592aa441e0f8de09b0912fea")
},
{
"title" : "Wise Man's Fear",
"pages" : 500,
"_id" : ObjectId("592aa441e0f8de09b0912feb")
},
},
{
"_id" : ObjectId("592aa441e0f8de09b0912fe9"),
"name" : "Rober Jordan",
"books" : [
{
"title" : "The Eye of the World",
"pages" : 400,
"_id" : ObjectId("592aa441e0f8de09b0912fea")
},
{
"title" : "The Great Hunt",
"pages" : 500,
"_id" : ObjectId("592aa441e0f8de09b0912feb")
}
},
我想查询所有作者中所有图书的列表-类似于:
And I would like to query for the list of all books in entire colletion of Authors - something like:
"books" : [
{
"title" : "The Eye of the World",
"pages" : 400,
"_id" : ObjectId("592aa441e0f8de09b0912fea")
},
{
"title" : "The Great Hunt",
"pages" : 500,
"_id" : ObjectId("592aa441e0f8de09b0912feb")
},
{
"title" : "Name of the wind",
"pages" : 400,
"_id" : ObjectId("592aa441e0f8de09b0912fea")
},
{
"title" : "Wise Man's Fear",
"pages" : 500,
"_id" : ObjectId("592aa441e0f8de09b0912fea")
}]
推荐答案
您可以使用 .aggregate()
,主要是 $unwind
管道运算符:
You can do this using .aggregate()
and predominantly the $unwind
pipeline operator:
In modern MongoDB 3.4 and above you can use in tandem with $replaceRoot
Model.aggregate([
{ "$unwind": "$books" },
{ "$replaceRoot": { "newRoot": "$books" } }
],function(err,results) {
})
在早期版本中,您使用 $project
:
In earlier versions you specify all fields with $project
:
Model.aggregate([
{ "$unwind": "$books" },
{ "$project": {
"_id": "$books._id",
"pages": "$books.pages",
"title": "$books.title"
}}
],function(err,results) {
})
所以 $unwind
是您用来解构的内容或反规范化"数组条目以进行处理.有效地,这为数组的每个成员创建了整个文档的副本.
So $unwind
is what you use to deconstruct or "denormalise" the array entries for processing. Effectively this creates a copy of the whole document for each member of the array.
剩下的任务是关于仅"返回数组中存在的那些字段.
The rest of the task is about returning "only" those fields present in the array.
这不是一件很明智的事情.如果您打算只返回嵌入在文档数组中的内容,那么最好将这些内容放入单独的集合中.
It's not a very wise thing to do though. If your intent is to only return content embedded within an array of a document, then you would be better off putting that content into a separate collection instead.
在性能上要好得多,使用聚合框架将集合中的所有文档分开,仅列出数组中的那些文档即可.
It's far better for performance, pulling apart a all documents from a collection with the aggregation framework, just to list those documents from the array only.
这篇关于如何从所有文档中仅返回数组的嵌套文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!