'mongodb , how to push data to array in object?
{
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 .
Solution 1:[1]
Query1
- push at position 0 (start of the array)
update(
{"name": {"$eq": "jeet"}},
{"$push":
{"data.frds": {"$each": [{"id": 10, "name": "john"}], "$position": 0}}})
Query2
- you can do it also with update pipeline, to add on start
- puts the new element it at first of the array
update(
{"name": {"$eq": "jeet"}},
[{"$set":
{"data.frds":
{"$concatArrays": [[{"id": 10, "name": "john"}], "$data.frds"]}}}])
Solution 2:[2]
you can use $push method working example
db.collection.update(
{ _id : ObjectId("yourid")}, //in your case use whatever is unique
{ $push: {"data.frds": {
id:value,
name: value2
}}}
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
