【问题标题】:Looping through array and running Mongo queries to modify same array循环遍历数组并运行 Mongo 查询以修改相同的数组
【发布时间】:2023-03-15 11:42:01
【问题描述】:

我有一个集合“用户”,其中包含类似的文档

{
    _id:ObjectId("xx"),
    searches:[
        {someId:"yyy","fav_food":"pasta"},
        {someId: "zzz","fav_food":"macncheese"}
    ]
}

someId 映射到另一个集合“job”

{
_id:yyy,
job_name:"clerk",
"name": "kent"
},
{
_id:zzz,
job_name:"racer",
"name":"michael"
}

我必须从作业集合中增强用户集合中的数据

所以用户文档应该是:

{
    _id:ObjectId("xx"),
    searches:[
        {someId:"clerk::kent",fav_food:"pasta"},
        {someId: "michael::racer","fav_food":"macncheese"}
    ]
}

我有

    mongo_db.collection('job', function(err,coll){
        for(var i = 0; i <= data.searches.length-1; i++) {
            var pid = data.searches[i].someId;
            console.log("RELEASE ID " + someId);

            if(pid !== null || pid !== undefined){
                result =  coll.findOne({"_id":ObjectId(pid)});
                if(result){
                    console.log("this is data searches for index " + i+ " " + JSON.stringify(data.searches[i]) 
                            + " and data.searches " + JSON.stringify(data.searches) + " and this is result " + JSON.stringify(result));
                    data.searches[i].someId =  result.name + "::" + result.job_name;


                }
            }
        }
        return data;
    })

这似乎不起作用...任何想法我该怎么做?我知道我必须使用 Promises/Async 函数,但我似乎找不到正确的组合。

【问题讨论】:

标签: node.js mongodb promise bluebird


【解决方案1】:

只需使用 mongo aggregate 即可。它给出了您预期的结果。试一试

db.getCollection('user').aggregate([
{
$unwind:{
    path:"$searches",
    preserveNullAndEmptyArrays:true
    }
},
{
$lookup:{
    from:"job",
    localField:"searches.someId",
    foreignField:"_id",
    as:"details"
    }
},
{
$unwind:{
    path:"$details",
    preserveNullAndEmptyArrays:true
    }
},
{
$group:{
    _id:"$_id",
    searches:{
        $push:{
            someId:{ $concat: [ "$details.job_name", "::", "$details.name" ] },
            fav_food:"$searches.fav_food"
            }
        }
    }
}
])

结果

{
"_id" : ObjectId("5cdb9dce6b57e490aaee734a"),
"searches" : [ 
    {
        "someId" : "clerk::kent",
        "fav_food" : "pasta"
    }, 
    {
        "someId" : "racer::michael",
        "fav_food" : "macncheese"
    }
]
}

【讨论】:

    【解决方案2】:

    如果您可以在 mongodb 聚合查询中执行此操作,则根本不需要在 javascript 中执行此操作。如下所示:

    db.user.aggregate([{
        $unwind: "$searches"
      },
      {
        $lookup: {
          from: "job",
          localField: "searches.someId",
          foreignField: "_id",
          as: "search"
        }
      },
      {
        $unwind: "$search"
      },
      {
        $group: {
          _id: "$_id",
          searches: {
            $addToSet: {
              "fav_food": "$searches.fav_food",
              "someId": {
                $concat: ["$search.name", '::', "$search.job_name"]
              }
            }
          }
        }
      }
    ])

    【讨论】:

      【解决方案3】:

      检查 cmets:

      //1. Below code snippet can optimize your task
      //2. You will be able to return desire result
      
      mongo_db.collection('job', function(err, coll) {
          var pid = [];
          for (var i = 0; i <= data.searches.length - 1; i++) {
              pid.push(data.searches[i].someId); //!! gather all the pids in array
              // console.log("RELEASE ID " + someId);
          }
          if (pid !== null || pid !== undefined) {
              // result = coll.findOne({ "_id": ObjectId(pid) });
      
              //!! Search all the data with $in agg. in one step
              //!! In this find all data's callback do your further task
      
              if (result) {
                  //!! loop thru the result and make your desire array
                  console.log("this is data searches for index " + i + " " + JSON.stringify(data.searches[i]) +
                      " and data.searches " + JSON.stringify(data.searches) + " and this is result " + JSON.stringify(result));
                  data.searches[i].someId = result.name + "::" + result.job_name;
                  // !! retrun the data after loop
                  return data;
              }
          }
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-22
        • 2023-03-22
        • 1970-01-01
        • 2017-08-16
        • 2011-07-16
        • 1970-01-01
        • 2018-02-19
        • 1970-01-01
        相关资源
        最近更新 更多