Home > Net >  How to merge two collections in mongodb, aggregate mongodb
How to merge two collections in mongodb, aggregate mongodb

Time:01-29

I have 2 collections: configs and points The points collection has a name field that stores the id for the configs collection

How can two collations be combined, given that the collection has an Array in which the objects in which to search.

configs:

{
    "find": true,
    "points": [{
        "image": true,
        "brand": true,
        "_id": {
            "$oid": "61f0ad909535d94c98056e11"
        },
        "name": "ABC"
    }, {
        "image": true,
        "brand": true,
        "_id": {
            "$oid": "61f0ade99535d94c98056e17"
        },
        "name": "Odido"
    }]
}

points

{
    "name": "61f0ad909535d94c98056e11",
    "userID": "61c49f94a02ff82b484cc6d0",
    enter code here
    "create_date": {
        "$date": "2022-01-27T02:53:52.473Z"
    }
}

I would like to get this result, well, or something similar

{
    "name": "61f0ad909535d94c98056e11",
    "userID": "61c49f94a02ff82b484cc6d0",
    "config_name": {
        "image": true,
        "brand": true,
        "_id": {
            "$oid": "61f0ad909535d94c98056e11"
        },
        "name": "ABC"
    },
    "create_date": {
        "$date": "2022-01-27T02:53:52.473Z"
    }
}

i am trying to use query like this

    Points.aggregate([
          {
            $lookup: {
              from: "configs",
              localField: "name",
              foreignField: "_id",
              as: "configs",
            },
          },
        ]);

Thanks in advance for your help :)

CodePudding user response:

db.points.aggregate([
  {
    $match: { "name": "61f0ad909535d94c98056e11" }
  },
  {
    $set: { "name": { "$toObjectId": "$name" } }
  },
  {
    $lookup: {
      from: "configs",
      localField: "name",
      foreignField: "points._id",
      as: "config_name"
    }
  },
  {
    $set: {
      "config_name": {
        "$first": {
          "$filter": {
            "input": { "$first": "$config_name.points" },
            "as": "item",
            "cond": { "$eq": [ "$name", "$$item._id" ] }
          }
        }
      }
    }
  }
])

mongoplayground

  •  Tags:  
  • Related