Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb Mongo合并到数组中_Mongodb_Mongodb Query_Aggregation Framework - Fatal编程技术网

Mongodb Mongo合并到数组中

Mongodb Mongo合并到数组中,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我有以下资料: {_id: blah, anotherId: "externalId", description: "foo"}, {_id: blah, anotherId: "externalId", description: "bar"}, ... 我想: {_id: blah, anotherId: "externalId", descriptions: ["foo", "bar"]} 我知道我可以简单地写这篇文章,但速度很慢,因为我有数百万条记录 db.collectionO

我有以下资料:

 {_id: blah, anotherId: "externalId", description: "foo"},
 {_id: blah, anotherId: "externalId", description: "bar"},
 ...
我想:

{_id: blah, anotherId: "externalId", descriptions: ["foo", "bar"]}
我知道我可以简单地写这篇文章,但速度很慢,因为我有数百万条记录

db.collectionOfAnotherId.find().forEach(function(r){ 
    var x = {anotherId: r.id, descriptions: []};
    db.myCollection.find({anotherId: x.anotherId}).forEach(function(d){
         x.descriptions.push(d.description); }); 
         db.newCollection.save(x); 
     })

有什么想法吗

您可以为此使用聚合框架。例如,考虑使用<强> <强>运算符进行左连接到<代码> MyCuffy<代码>,并使用<强> < /强>将以下<强> < /强>管道的结果写入到新集合中,以创建描述数组为:

db.collectionOfAnotherId.aggregate([
    {
        "$lookup": {
            "from": "myCollection",
            "localField": "id",
            "foreignField": "anotherId",
            "as": "d"
        }
    },
    { "$unwind": "$d" },
    {
        "$group": {
            "_id": "$_id",
            "anotherId": { "$first": "$id" },
            "descriptions": { "$push": "$d.description" }
        }
    },
    { "$out": "newCollection" }
])

我担心,伙计,你们得继续你们已经想到的想法。任何DBMS都很难提供这样的功能。如果该描述的值从一开始就是一个数组,那么您可以拥有一个包含所有唯一元素的集合数组,但是……是的,如果只考虑原始数据:)很漂亮!你认为这会比我简单的函数快吗。难道它不需要至少迭代两次数据吗?它可能会更快,我不知道,但有了聚合框架,它意味着提供更好的性能,测试起来非常容易,所以试试看效果如何。