Home > Net >  Mongodb "patching" one collection results from other colection
Mongodb "patching" one collection results from other colection

Time:01-31

I've got let's say one collection "users":

[{ "User" : 
  { id: "1",
    phone: "111 111 111",
    login: "abc"
  },
  "Address" :
  { street: "Street",
    town: "NY"
  }
},
{ "User" : 
  { id: "2",
    phone: "222 222 222",
    login: "xyz"
  },
  "Address" :
  { street: "Street",
    town: "NY"
  }
}]

And now I have "updates" collection:

[{ "User" :
  { id: "1" },
   "Address": 
   { town: "LA" }
}]

All have common User.id field.

Now I'm trying to get data from "users" but updated with fields from "updates".

{ "User" : 
  { id: "1",
    phone: "111 111 111",
    login: "abc"
  },
  "Address" :
  { street: "Street",
    town: "LA" // <--- updated
  }
}  

I want to use it in a Atlas function attached to an endpoint.

I tried:

aggregate([
  {
    $match: {
      "User.id": id
    }
  },
  {
    $lookup: {
      from: "updates",
      localField: "User.id",
      foreignField: "User.id",
      as: "updates"
    }
  }

And I get additional "updates" where it exists, but with extra fields. How original "users" fields values map/override with values from "updates" when they're there?

CodePudding user response:

You can use $mergeObjects. You will need extra $mergeObjects for individual nested document fields(e.g. Users)

db.users.aggregate([
  {
    $match: {
      "User.id": "1"
    }
  },
  {
    $lookup: {
      from: "updates",
      localField: "User.id",
      foreignField: "User.id",
      as: "updatesLookup"
    }
  },
  {
    "$unwind": {
      path: "$updatesLookup",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          "$$ROOT",
          "$updatesLookup",
          {
            User: {
              "$mergeObjects": [
                "$User",
                "$updatesLookup.User"
              ]
            }
          }
        ]
      }
    }
  },
  {
    $unset: "updatesLookup"
  }
])

Mongo Playground

  • Related