mongodb update all document with incrementing the value by 1 [duplicate] - mongodb

This question already has an answer here:
Multiple $inc updates in MongoDB
(1 answer)
Closed 4 years ago.
i have several document in mongoDB, doc structure is like this
{
"a":"abc",
"myid":2
}
I want to update "myid" of all document with 1. for example for 1st document myid = 1, for second document myid =2 and so on. Is there a query?

Try this query:
db.collection.updateMany(
{},
{$inc:{myid:1}}
)

Create a separate Collection called Counter to track the last sequence number.
db.counters.insert(
{
_id: "userid",
seq: 0
});
And create a function to fetch seq value for Counter collection.
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true
});
return ret.seq;
}
And Increment your auto-increment field like below.
db.collection.insert({
"a":"abc",
"myid": getNextSequence("userid")
});
I hope this will help you.

Related

How to update each document with one query in mongodb [duplicate]

This question already has an answer here:
How to update each value with one query in mongodb
(1 answer)
Closed 3 years ago.
I have a data as below.
// first document
{
"id": 1,
"exist": true
}
// second document
{
"id": 2,
"exist": false
}
// third document
{
"id": 3,
"exist": false
}
When I findOneAndUpdate({_id:2}),{exist:true}), I hope that exist of 'id:1' is changed to false automatically in one query using aggregate or etc.
could you recommend some idea for it? Thank you so much for reading my question.
I don't really understand what do you want to update in your collection but to update many document use updateMany :
db.collection.updateMany(
{ violations: { $gt: 1 } }, // the filter to select the wanted document
{ $set: { "exist" : true } } // the change to apply to the field
);

How to return only the updated subdocument inside of array after an update [duplicate]

This question already has answers here:
Mongoose select fields to return from findOneAndUpdate
(7 answers)
Retrieve only the queried element in an object array in MongoDB collection
(18 answers)
Closed 3 years ago.
I have a user model with the following schema
{
_id: userId,
inbox: {
inbox: [Array of message documents],
sent: [Array of message documents],
}
}
Is there a way to get only the updated subdocument after an update in mongodb / mongoose ?
The update is good i just want to return the updated subdocument instead of querying the db again
db.getCollection("users").findOneAndUpdate(
{ "inbox.sent._id": ObjectId("5cea23be8c03c800d43a8376") },
{ "$set": { "inbox.sent.$.inTrash": false } },
{ "inbox.sent.$": 1 } <-- how to return only the subdocument like in a query
);
expected output the array at inbox.sent with only the updated doc
{
_id: userId,
inbox: {
sent: [{ updated doc}]
}
}
You need to apply a callback to the findOneAndUpdate function
e.g:
db.getCollection("users").findOneAndUpdate(
{ "inbox.sent._id": ObjectId("5cea23be8c03c800d43a8376") },
{ "$set": { "inbox.sent.$.inTrash": false } },
{ "inbox.sent.$": 1 },
function (err, res) {
//here you have the res, which will be the affected record
}
);

MongoDB update nested array of object by index [duplicate]

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){
});

mongodb: insert item into array only if a certain field is not present [duplicate]

This question already has answers here:
Can you specify a key for $addToSet in Mongo?
(2 answers)
Closed 8 years ago.
I have a data model which looks like this
{
_id: 1
some_property: some_value
items: [
{
item_id: item1
item_properties: [
{
key1: val1,
key2: val2
}]
}]
}
When I get a new item with item_id=itemX, I would like to check if an item with this item_id is in the items array. If it's not present, then insert it. If it is present, i would like to append the item_properties to the existing item_properties.
I tried using $addToSet, but this considers the entire item and not the item_id itself. So the result was 2 items with the same item_id.
Any idea how i can achieve this atomically?
Thanks,
Aliza
The following codes can run atomically, I think.
function doWhenItemExisted() {
var n = db.c.update({
"items.item_id" : itemX
}, {
$pushAll: { // I think item_properties of given item is also an array
"items.$.item_properties" : item.item_properties
}
}).nModified;
if (!n) {
doWhenItemNotExisted();
}
}
function doWhenItemNotExisted() {
var n = db.c.update({
"items.item_id" : {
$ne : itemX
}
}, {
$push: {
"items" : item
}
}).nModified;
if (!n) {
doWhenItemExisted();
}
}
// entry
doWhenItemExisted();

Increment all element in nested array [duplicate]

This question already has answers here:
How to Update Multiple Array Elements in mongodb
(16 answers)
Closed 8 years ago.
I have a document like that :
{
_id: ".....",
messages: [
{
....
votes: 2
},
{
....
votes: 2
}
]
}
I would like to increment ALL votes field in the array in the same request.
How to do that ? The $ operator select only the first element.
Thank you !
You might have to do this with some JS loops:
db.collection.find( { "_id": SOME_ID } ).forEach( function( doc ) {
for ( i in doc.messages ){
doc.messages[ i ].votes += 1;
}
db.collection.save( doc );
} );
What I'm doing here is iterating over each document in the cursor and iterating over it's messages property incrementing each element's votes attribute by one.