Mongo how to $lookup with DBRef

后端 未结 2 578
再見小時候
再見小時候 2020-11-27 17:21

I have a trouble(/(ㄒoㄒ)/~~). Suppose that collection A is

{ 
    \"_id\" : ObjectId(\"582abcd85d2dfa67f44127e1\"), 
    \"bid\" : [
        DBRef(\"B\",         


        
2条回答
  •  再見小時候
    2020-11-27 17:40

    As of mongoDB 3.4, this is not possible. You can't use DBRef in the aggregation pipeline, except in the $match stage.

    I strongly recommend you to get rid of DBRef and switch to manual references. However, if you really need to keep DBRef, here is an (ugly) solution:

    first, create a new collection named "C", where DBRefs are replaced by their Ids using mapReduce:

    db.A.mapReduce(
        function() {
            var key = this._id; 
            var value = [];  
            for ( var index = 0; index < this.bid.length; index++){
               value.push(this.bid[index].$id); 
            }
            emit(key, value); 
        },
        function(key,values) {
            return  values;
        },
        {
            "query": {},
            "out": "C" 
        }
    )
    

    then, run your aggregation query on the new "C" collection:

    db.C.aggregate([
       {
          $unwind:"$value"
       },
       {
          $lookup:{
             from:"B",
             localField:"value",
             foreignField:"_id",
             as:"bs"
          }
       }
    ]);
    

    output:

        {
           "_id":ObjectId("582abcd85d2dfa67f44127e1"),
           "value":ObjectId("582abcd85d2dfa67f44127e0"),
           "bs":[
              {
                 "_id":ObjectId("582abcd85d2dfa67f44127e0"),
                 "status":1,
                 "seq":0
              }
           ]
        }{
           "_id":ObjectId("582abcd85d2dfa67f44127e1"),
           "value":ObjectId("582abcd85d2dfa67f44127e1"),
           "bs":[
              {
                 "_id":ObjectId("582abcd85d2dfa67f44127e1"),
                 "status":1,
                 "seq":0
              }
           ]
        }
    

提交回复
热议问题