我在 mongoDB 中有一个深度嵌套的文档,我想获取单个子对象。
例子:
{
"schoolName": "Cool School",
"principal": "Joe Banks",
"rooms": [
{
"number": 100
"teacher": "Alvin Melvin"
"students": [
{
"name": "Bort"
"currentGrade": "A"
},
// ... many more students
]
},
// ... many more rooms
]
}
最近 Mongo 更新为允许使用$elemMatch 投影进行 1 级深度子对象检索:
var projection = { _id: 0, rooms: { $elemMatch: { number: 100 } } };
db.schools.find({"schoolName": "Cool School"}, projection);
// returns { "rooms": [ /* array containing only the matching room */ ] }
但是当我尝试以同样的方式获取一个学生(2 级深)时,我得到一个错误:
var projection = { _id: 0, "rooms.students": { $elemMatch: { name: "Bort" } } };
db.schools.find({"schoolName": "Cool School"}, projection);
// "$err": "Cannot use $elemMatch projection on a nested field (currently unsupported).", "code": 16344
有没有办法在 mongoDB 文档中检索任意深度的子对象?
我正在使用 Mongo 2.2.1