简体   繁体   中英

How to merge two collections in mongodb, aggregate mongodb

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:)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM