【发布时间】:2018-07-17 18:32:19
【问题描述】:
{
"_id" : ObjectId("5b4d815ad85250f4e502d142"),
"company_Name" : "Rishabh Instruments",
"spaces" : [
{
"_id" : "11",
"name" : "Trishala",
"spaces" : [
{
"_id" : "111",
"name" : "ESL"
},
{
"_id" : "112",
"name" : "IS"
}
]
},
{
"_id" : "12",
"name" : "Riddhi",
"spaces" : [
{}
]
},
{
"name" : "XYZ",
"spaces" : [
{}
]
}
]
}
这是我在 Mongo DB 中的文档结构,它可能包含最高第 N 级的子文档,所以现在我想访问以 ESL 和 IS 命名的文档。那么我该怎么做才能通过以下查询升到第二级
db.space.aggregate([
{$match: {company_Name: 'Rishabh Instruments'}},
{$unwind: '$spaces'},
{$match: {'spaces.name': 'Trishala'}}
// {$unwind: '$spaces'},
// {$match: {'spaces.name': 'ESL'}}
])
但是如果我取消注释这两行,那么它不会返回任何东西 所以任何人都可以指导我或给出任何提示。
【问题讨论】:
-
在
$match中,您可以使用常规查询语法。你不能从那里建立起来吗?参见例如:docs.mongodb.com/manual/tutorial/query-array-of-documents -
您能否提供一个示例输出,您希望响应结构应该是什么?
-
期望输出像 { "_id" : "111", "name" : "ESL" }, { "_id" : "112", "name" : "IS" }
标签: mongodb