Home > front end >  mongodb , how to push data to array in object?
mongodb , how to push data to array in object?

Time:03-11

{
  name: "jeet",
  address: "Highway 71",
  data: {
    connnection: 2,
    frds: [
      // push here.
      {
        id: 8349,
        name: "manoj"
      },
      {
        id: 3232,
        name: "magan"
      }
    ]
  }
}

how to add value in array that belongs to an object .

CodePudding user response:

you can use $push method

db.collection.update(
        { _id : ObjectId("yourid")}, //in your case use whatever is unique
        { $push: {"data.frds": {
            id:value,
            name: value2
        }}}
    )

CodePudding user response:

Query

  • you can do it also with aggregate pipeline
  • puts the new element it at first of the array

PlayMongo

update(
{"name": {"$eq": "jeet"}},
[{"$set": 
   {"data.frds": 
     {"$concatArrays": [[{"id": 10, "name": "john"}], "$data.frds"]}}}])
  • Related