Home > Mobile >  Update data in mongo db with condition of another collection
Update data in mongo db with condition of another collection

Time:10-15

I have 2 collection in mongodb: Account, Information.

Account:

{
  "_id": {
    "$oid": "6348dc197a7b552660170d8b"
  },
  "username": "12345",
  "password": "123dsgfdsgdfsg",
  "email": "1243",
  "role": "123",
  "_infoid": {
    "$oid": "6348dc197a7b552660170d8a"
  }
}

Information:

{
  "_id": {
    "$oid": "6348dc197a7b552660170d8a"
  },
  "avatar": "hello",
  "name": "Abcd",
  "phonenumber": "012345678",
  "address": "abcd"
}

I wanna change "phonenumber" to "123" but I just have "_id" of Account. Can I change it with aggregation pipeline?

CodePudding user response:

You don't need to duplicate _id, findOneAndUpdate() can be executed for this use case.

The definition of it is:

db.collection.findOneAndUpdate( filter, update, options )

which updates a single document based on the filter and sort criteria.

Below you can refer to the link for more details: https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate/ .

CodePudding user response:

Performa a $lookup and perform some wrangling to your desired format. Finally do a $merge to update to the collection Information

db.Information.aggregate([
  {
    "$lookup": {
      "from": "Account",
      "localField": "_id",
      "foreignField": "_infoid",
      "pipeline": [
        {
          "$project": {
            role: 1
          }
        }
      ],
      "as": "AccountLookup"
    }
  },
  {
    "$unwind": "$AccountLookup"
  },
  {
    $set: {
      phonenumber: "$AccountLookup.role"
    }
  },
  {
    $unset: "AccountLookup"
  },
  {
    "$merge": {
      "into": "Information",
      "on": "_id",
      "whenMatched": "merge",
      "whenNotMatched": "discard"
    }
  }
])

Here is the Mongo Playground for your reference.

CodePudding user response:

Does this seem what you try to achieve?

// populate database with test data
use("test_db")

db.account.insertOne({
  "_id": "6348dc197a7b552660170d8b",
  "username": "12345",
  "password": "123dsgfdsgdfsg",
  "email": "1243",
  "role": "123",
  "_infoid": "6348dc197a7b552660170d8a"
})

db.information.insertOne({
  "_id": "6348dc197a7b552660170d8a",
  "avatar": "hello",
  "name": "Abcd",
  "phonenumber": "012345678",
  "address": "abcd"
})


// define some test variables to use
let some_account_id = "6348dc197a7b552660170d8b"
let new_phone_number = " 9876543210"


// change data
db.account.aggregate([
  {
    $match: {_id: some_account_id}
  },
  {
    $addFields: {phonenumber: new_phone_number}
  },
  {
    $project: {phonenumber: 1, _id: "$_infoid"}
  },
  {
    $merge:{
      into: "information",
      whenNotMatched: "fail",
    }
  }
])

// show final results
db.information.find()

Result:

[
  {
    "_id": "6348dc197a7b552660170d8a",
    "avatar": "hello",
    "name": "Abcd",
    "phonenumber": " 9876543210",
    "address": "abcd"
  }
]

  • Related