【发布时间】:2023-03-28 11:23:01
【问题描述】:
我有一个包含文档的集合,这些文档由 id、名称和项目数组组成;每个文档中的数组在适用时应该嵌套相同结构的其他文档,并且文档的嵌套数组没有多少个限制(嵌套文档也可以有嵌套文档)。
使用 MongoClient 包,我正在尝试查询我的集合并根据它的 id 返回一个文档,而不管它在数据中的位置(无论是在顶层还是向下 3 层)。
到目前为止,我可以返回任何顶级数据,但我的查询没有找到任何嵌套数据。我看到过数据结构有限且一致的类似问题,但由于我的数据是动态的和多层的,我还没有找到适合这个特定问题的解决方案。
这是我的数据:
[
{
"_id": 1,
"name": "Test 1",
"items": []
},
{
"_id": 2,
"name": "Test 2",
"items": [
{
"_id": 3,
"name": "Test 3",
"items": []
},
{
"_id": 4,
"name": "Test 4",
"items": [
{
"_id": 6,
"name": "Test 6",
"items": []
}
]
}
]
},
{
"_id": 5,
"name": "Test 5",
"items": []
}
]
这是我的 Mongo 查询:
MongoClient.connect(connString, function(err, db) {
var collection = db.collection('items');
collection.findOne({_id: ObjectID("4")}, function(err, result) {
console.log(result);
});
db.close();
});
结果是打算返回以下内容,但返回null:
{
"_id": 4,
"name": "Test 4",
"items": [
{
"_id": 6,
"name": "Test 6",
"items": []
}
]
}
谁能分享我如何按预期检索数据的解决方案?
【问题讨论】:
标签: mongodb