Update a mongodb document and get the updated document [duplicate] - mongodb

This question already has answers here:
Update And Return Document In Mongodb
(7 answers)
Mongoose: findOneAndUpdate doesn't return updated document
(16 answers)
Closed 3 years ago.
Using Express and MongoDB, how can I update a document, then get that updated document?
The following code will find the profile document with the given user.id, then remove the experience with the given exp_id from the experience array. However, it returns the original profile (including the removed experience), not the updated one.
let profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $pull: { experience: { _id: req.params.exp_id } } },
{ returnNewDocument: true }
)
console.log(profile); // logs the original profile, still incl the removed experience
What do I need to change for it to return the updated profile?
Docs: https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/

Related

Mongodb how to insert or update all? [duplicate]

This question already has answers here:
Spring Data Mongo: upsert with various fields updated
(1 answer)
Spring Data MongoDB and Bulk Update
(3 answers)
Closed 3 years ago.
Spring boot mongo repository support saveAll,but it cause unique index insert error ,so I want use update.
In my case,I want to insert or update 10 documents together.
how to use updateAll?
Though I'm not crystal clear on your question, it sounds like you need to append { multi: true } to your update query. Please see Update Multiple Documents.
Setting the multi option updates all documents found by match.
To update multiple documents, set the multi option to true. For
example, the following operation updates all documents where stock is
less than or equal to 10:
db.books.update(
{ stock: { $lte: 10 } },
{ $set: { reorder: true } },
{ multi: true }
)
you can use updateMany:
db.collections.updateMany({ query }, {"$set":{ update }}

How to update array with Meteor [duplicate]

This question already has answers here:
Push items into mongo array via mongoose
(11 answers)
Closed 4 years ago.
I'm trying to add an element in an array but can't figure out what is causing my problem,
Don't know if i have to do an insert or an update anyway tried both, both not working
addUserToArray:function(userId,_id,email){
check(_id, String)
check(userId,String)
check(email, String)
var current_test = Modules.test.checkTestExist(test_id);
const USER = Accounts.findUserByEmail(email)
let test=USER._id
if(userId==current_test.senders[0]){
Tests.update(_id, {$set: {'name': name}}) // this one getting updated
Tests.update(test_id, { $set: { "current_test.senders": test} }) // this is not working
}
i got the error
UserIds that can send messages on this test must be an array",
You just need to change the $set by $push
Tests.update(box_id, { "$push": { "current_test.senders": USER._id} })

updating multiple documents by passing a list objectids to findByIdAndUpdate [duplicate]

This question already has answers here:
MongoDB: How to update multiple documents with a single command?
(13 answers)
FindAndModify, return array of Objects
(1 answer)
Closed 5 years ago.
I am trying to use mongoose's findByIdAndUpdate method to pass in a list of object id's and updating them at once. However, I am getting a "Error: Can't use $set with ObjectId." error which I can't seem to associate with my code.
Here's my code.
return ComponentModel.findByIdAndUpdate({
_id: {
$in: input.subjectIds
},
$set: { location: input.newLocation }
}).then(res => res);
findByIdAndUpdate is for one document. For multiple documents you can use update with multi flag true.
return ComponentModel.update(
{_id: {$in: input.subjectIds}},
{$set: {location: input.newLocation}},
{"multi": true}
).then(res => res);

Updating Every Record in Mongo [duplicate]

This question already has answers here:
Update MongoDB field using value of another field
(12 answers)
Closed 6 years ago.
How would I update every record in the "title" collection for mongo, to make a field named LastReturnedName set to Name for every single record?
Thought it would be something like this:
db.title.update(
{ "LastNameReturned" : "" },
{ $set:{ "LastNameReturned" : Name } },
{ multi : true }
);
You can use foreach iteration:
db.title.find({ "LastNameReturned" : "" }).snapshot()
.forEach(function(t) {
db.title.update({_id: t._id}, {$set: {"LastNameReturned" : t.Name}});
});
NOTE: You can use snapshot() only with unsharded collections. Also you can speed up updating if you'll use bulk operation.

Mongoose: how to update *all* persons matching a condition? [duplicate]

This question already has answers here:
How can I update multiple documents in mongoose?
(7 answers)
Closed 7 years ago.
I have do do something like this (please forgive me about the stupidity of the example... :-):
var dateRef = new Date(1990, 1, 1);
Person
.where('dateOfBirth').gte(dateRef)
.update({ $set: { isYoung: true } }, function (err, count) {
})
;
I.e.: I'd like to $set to true field isYoung for every Person document whose date of birth (dateOfBirth) is later than a reference date.
My code is working for just one person, even if (currently) many documents do match the condition (all young people, here... :-).
Any clue?
P.S.: as a bonus, I'd like to set not-matching persons isYoung field to false, too, if possible...
You should use multi:true in update to update multiple documents like :
var dateRef = new Date(1990, 1, 1);
Person
.where('dateOfBirth').gte(dateRef)
.update({ $set: { isYoung: true } },{multi: true}, function (err, count) {
});