MongoDB update nested array of object by index [duplicate] - mongodb

This question already has answers here:
Update field in exact element array in MongoDB
(5 answers)
Closed 5 years ago.
Let's suppose to there is db like below...
{ _id: 1234,
key: 'Contacts',
value: [
{ name: 'McDonald', phone: '1111'},
{ name: 'KFC', phone: '2222'}
]
}
And I want to change KFC's phone number to '3333'.
What I did is
DB.findOne({ key: 'Contacts' }, function(err, db){
db.value[1]['phone'] = '3333'
db.save(function(err, result){
// done
})
}
)
But it didn't update the database. What am I wrong?
There's no specific _id in elements of array for some reason.
Only the way to find specific element is index.

Use the positional operator $
more info : https://docs.mongodb.com/manual/reference/operator/update/positional/#up.S
DB.update({key: "Contacts", "value.name": "KFC" },
{ $set: { "value.$.phone" : 666 } },function(err,doc){
});

Related

How to update nested object property in MongoDB [duplicate]

This question already has answers here:
MongoDB - Update an object in nested Array
(4 answers)
Closed 1 year ago.
I have a data on MongoDB database which structure is
{
_id: 12478565,
products: { name: 'Mackbook Pro', price: 150000, color: 'silver' }
}
I want to update the products price and I write like this, but it gives an error
productsCollection.updateOne({_id: '12478565'}, {$set: {products.price: 190000} })
I want to know how can I modify the data in nested object?
put product.price in qoute
db.collection.update({
_id: "12478565"
},
{
$set: {
"products.price": 190000
}
})
https://mongoplayground.net/p/QxAK0LClF-8

Remove element of internal field array MongoDb [duplicate]

This question already has answers here:
MongoDB, remove object from array
(7 answers)
Closed 4 years ago.
I have the following situation:
{ code: 0, array:[{ _id: 1, ....}, { _id: 2, ....}, { _id: 18, ....}]}
I need to remove the element inside 'array' field matching the '_id' field.
How can I do that?
Thank you.
Use $update & $pull:
db.yourCollection.update(
{ }, // <-- your selection criteria
{ $pull: { array: { _id: 2 } } // <-- what you want to remove from which field
)

MongoDB : Update document array value object [duplicate]

This question already has answers here:
How to Update Multiple Array Elements in mongodb
(16 answers)
Closed 5 years ago.
I have document like below
{
_id="12345",
details:[
{
name:"Customer_Name",
time:"request_time"
},
{
name:"Customer_Name",
time:"request_time"
},
{
name:"Customer_Name",
time:"request_time"
}, ....
]
}
I want to update "name" field in all the objects of "details" array.
I can use it update each array object using
db.customer.updateMany({_id:"12345"},{$set:{"details.0.name":"My_Name"}});
Is there any way to update all of them at once
Try:
db.customer.find({ _id:"12345" })
.forEach(function (doc) {
doc.details.forEach(function (details) {
details.name="My_Name";
});
db.customer.save(doc);
});

MongoDB find then query nested document [duplicate]

This question already has answers here:
Retrieve only the queried element in an object array in MongoDB collection
(18 answers)
Closed 5 years ago.
I'm trying to make a 'like' route that find user by _id then query inside user.post an object id, so far I tried this:
User.find({
"_id": logged_user,
"posts_id": {
$elemMatch: req.body.id
}
}, (err, data) => {
if (err) {
res.json(err)
}
console.log(data);
})
Schema:
username: String,
posts:[{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
it returns an empty array '[]', how can I return true of false if it exists?
You are using $elemMatch wrong. It needs an object. Do it this way:
User.find({"_id":logged_user,"posts":{$elemMatch: {$eq : req.body.id}}},(err,data)=>{
if(err){
res.json(err)
}
console.log(data);
)

mongoDB: check if value exists in specific subdocument array [duplicate]

This question already has answers here:
Retrieve only the queried element in an object array in MongoDB collection
(18 answers)
Closed 5 years ago.
I have the following schema:
{
_id: objectID('593f8c591aa95154cfebe612'),
name: 'test'
businesses: [
{
_id: objectID('5967bd5f1aa9515fd9cdc87f'),
likes: [objectID('595796811aa9514c862033a1'), objectID('593f8c591ba95154cfebe790')]
}
{
_id: objectID('59579ff91aa9514f600cbba6'),
likes: [objectID('693f8c554aa95154cfebe146')]
}
]
}
How can I check if objectID('593f8c591ba95154cfebe790') exists in the array business.likes where businesses._id = objectID('59579ff91aa9514f600cbba6') ?
In the above example it should return false.
You can use $elemMatch to find by multiple field in same sub document
db.collectionName.find({
businesses: {
$elemMatch: {
_id: ObjectId("5967bd5f1aa9515fd9cdc87f"),
likes: ObjectId("593f8c591ba95154cfebe790")
}
}
});