MongoDB嵌套对象集合查找
我对MongoDB(运行3.4)和Node.js相当陌生,并且遇到了相关数据的困难。 我有集合A
, B
, C
,其中A
引用数组中的某些B
,而B
引用数组中的某些C
现在我正试图读取所有的A
而所有包含的文件加载。 两个左连接,可以这么说。 以下是一些数据示例:
collectionsA:
[{ _id: 1, name: "A one", bs: [ 11, 12 ] },{ _id: 2, name: "A two", bs: [ 12 ] }]
collectionsB:
[{ _id: 11, name: "B one", bs: [ 21, 22 ] },{ _id: 12, name: "B two", bs: [ 21 ] }]
collectionsC:
[{ _id: 21, name: "C one" },{ _id: 22, name: "C two" }]
我期望的结果是:
[{ _id: 1, name: "A one", bs: [{ _id: 11, name: "B one", bs: [{ _id: 21, name: "C one" },{ _id: 22, name: "C two" }] },{ _id: 12, name: "B two", bs: [ { _id: 21, name: "C one" } ] }] },{ _id: 2, name: "A two", bs: [ { _id: 12, name: "B two", bs: [ { _id: 21, name: "C one" } ] } ] }]
但是随着我的尝试,这是行不通的。 试图“join”一些额外的领域“foundBs”和“foundCs”首先。
db.collection('A').aggregate([ { $lookup: { from: 'B', localField: 'bs', foreignField: '_id', as: 'foundBs' } }, { $lookup: { from: 'C', localField: 'cs', foreignField: '_id', as: 'foundCs' } } ], function(err, res) { console.log(JSON.stringify(res)); });
你能帮忙吗? 除了这个问题,你是否会build议使用MongoDB来快速构build原型,而且内容和结构要快速变化呢?还是应该使用这样的相关数据呢?