1

I have following collections: Collection A

{
    "_id" : ObjectId("5aaa3b170e26ed1eba223ba9"),
    "name" : "A1",
    "ref" : {
        "$ref" : "B",
        "$id" : ObjectId("5aaa33740e26ed1eba223ba1")
    }
}
{
    "_id" : ObjectId("5aaa3b170e26ed1eba223baa"),
    "name" : "A2",
    "ref" : {
        "$ref" : "C",
        "$id" : ObjectId("5aaa33740e26ed1eba223ba2")
    }
}

Collection B

{
    "_id" : ObjectId("5aaa33740e26ed1eba223ba1"),
    "name" : "B1"
}
...

Collection C

{
       "_id" : ObjectId("5aaa33740e26ed1eba223ba2"),
       "name" : "C1"
}
...

It is posable to get folowing result?

{
    "_id" : ObjectId("5aaa3b170e26ed1eba223ba9"),
    "name" : "A1",
    "result" : [ 
        {
            "name" : "B1"
        }
    ]
}
{
    "_id" : ObjectId("5aaa3b170e26ed1eba223baa"),
    "name" : "A2",
    "result" : [ 
        {
            "name" : "C1"
        }
    ]
}

I tried it with $Project and §Lookups, unfortunately withou success. Hire is example:

db.A.aggregate([
  {$project: { 
    name : 1,
    refId: {$arrayElemAt: [{$objectToArray:"$ref"},1]},
    refCol: {$arrayElemAt: [{$objectToArray:"$ref"},0]},
  }
},
  {$lookup : {
     from : "refCol.v",
     localField : "refId.v",
     foreignField : "_id",
     as : "result"
     }
  },
  {$project : {"result._id" : 0, refId : 0, refCol : 0}} 
])

In this example I can't reference the "refCol.v" field in the $lookup function. Have someone a tip or a better solution for me?

ahux
  • 41
  • 5

1 Answers1

0

You can achieve this by populate() method:

const collectionA = require('../models/collectionA');

collectionA.find({}).populate({
   path: 'collectionB',
   select: {
       'name': 1,
       '_id': 0
   }
   })
 }).then((data) => {
   if (data) {
       res.send(data);
   }
}).catch((err) => {
    res.send(err);
})
Neel Rathod
  • 2,013
  • 12
  • 28
  • Hi Neel Rathod, thank you for your tip but if i right understand it's a _JavaScript_ solution and i work with a ,net driver! – ahux Mar 19 '18 at 09:10