0

My first collection value is :

Collection 1:

{
   _id:"5f82f1618cfa6d290c6271a9",
   name:"mehdi"
}

And second collection value is :

Collection 2:

{
    _id:"5f82f1618cfa6d290c6271aa",
    fid:"5f82f1618cfa6d290c6271a9",
    family:"parastar"
}

How can I populate base on _id in coll1 and fid in coll2?

I want to be, result like this:

{
   {
    _id:"5f82f1618cfa6d290c6271aa",
    fid:"5f82f1618cfa6d290c6271a9",
    family:"parastar"
   },
   name:"mehdi"
}

do you have any idea to do this?

J.F.
  • 13,927
  • 9
  • 27
  • 65
mehdi parastar
  • 737
  • 4
  • 13
  • 29

1 Answers1

0

You have to use $lookup in this way:

db.coll1.aggregate([
  {
    $lookup: {
      from: "coll2",
      localField: "_id",
      foreignField: "fid",
      as: "collection"
    }
  }
])

This query create a field called collection with the data you want:

[
  {
    "_id": "5f82f1618cfa6d290c6271a9",
    "collection": [
      {
        "_id": "5f82f1618cfa6d290c6271aa",
        "family": "parastar",
        "fid": "5f82f1618cfa6d290c6271a9"
      }
    ],
    "name": "mehdi"
  }
]

Example here

Using Mongoose is the same, only write the query like this:

var agg = await model.aggregate([
    {
      $lookup: {
        from: "coll2",
        localField: "_id",
        foreignField: "fid",
        as: "collection"
      }
    }
  ])
console.log(agg)
J.F.
  • 13,927
  • 9
  • 27
  • 65
  • thanks, but I can't use aggregate because of my collections in separate databases :( – mehdi parastar Jan 18 '21 at 04:54
  • This is a very important detail because is not possible. Check this [answer](https://stackoverflow.com/a/65754304/13464279) then. Also [Jira ticket](https://jira.mongodb.org/browse/SERVER-34935) is open so it is not resolved. – J.F. Jan 18 '21 at 07:30