MongoDB嵌套对象集合查找

时间:2017-11-17 20:24:12

标签: arrays node.js mongodb nested lookup

我是MongoDB(运行3.4)和Node.js的新手,我对相关数据有困难。我有集合ABC,其中A引用数组中的某些BB引用某些C A 1}}在一个数组中。现在我尝试在加载所有包含的文档时读取所有[{ _id: 1, name: "A one", bs: [ 11, 12 ] },{ _id: 2, name: "A two", bs: [ 12 ] }] 个。两个左连接,可以这么说。以下是一些数据示例:

收藏A:

[{
    _id: 11,
    name: "B one",
    bs: [ 21, 22 ]
},{
    _id: 12,
    name: "B two",
    bs: [ 21 ]
}]

收集B:

[{
    _id: 21,
    name: "C one"
},{
    _id: 22,
    name: "C two"
}]

收藏C:

[{
    _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"
        } ]
    } ]
}]

我期望的结果是:

  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));
  });

但是我的尝试,它不起作用。试图首先在“foundBs”和“foundCs”的一些额外字段中“加入”。

        Queue<Node> queue = new LinkedList<>();
        queue.add(root);

        Node leftMost = null;
        while (!queue.isEmpty()) {
            Node node = queue.poll();

            if (leftMost == node) {
                System.out.println();
                leftMost = null;
            }

            System.out.print(node.getData() + " ");

            Node left = node.getLeft();
            if (left != null) {
                queue.add(left);
                if (leftMost == null) {
                    leftMost = left;
                }
            }

            Node right = node.getRight();
            if (right != null) {
                queue.add(right);

                if (leftMost == null) {
                    leftMost = right;
                }
            }
        }
你帮帮忙吗? 除了这个问题,您是否建议使用MongoDB以快速更改内容和结构进行快速原型设计,还是应该使用具有此类相关数据的旧SQL?

0 个答案:

没有答案