0

I want to update sth together, allow operation on the same document more than once

for example, $inc 'csize' column X times if document's _id appear X times

but mongodb only work for once, how to do deal with this ?

or other solutions without $in ?

> db.user_info.findOne({_id:ObjectId("54bcc154ed9c800af1d11b47")})
{
        "_id" : ObjectId("54bcc154ed9c800af1d11b47"),
        "atime" : ISODate("2015-04-03T07:10:24.118Z"),
        "csize" : 25
}
> db.user_info.update({_id:{$in:[
        ObjectId("54bcc154ed9c800af1d11b45"),
        ObjectId("54bcc154ed9c800af1d11b45"),
        ObjectId("54bcc154ed9c800af1d11b46"),
        ObjectId("54bcc154ed9c800af1d11b47"),
        ObjectId("54bcc154ed9c800af1d11b47"),
        ObjectId("54bcc154ed9c800af1d11b47")
    ]}},
    {$inc: {csize:1}},
    true,
    true
)

> db.user_info.findOne({_id:ObjectId("54bcc154ed9c800af1d11b47")})
{
        "_id" : ObjectId("54bcc154ed9c800af1d11b47"),
        "atime" : ISODate("2015-04-03T07:10:24.118Z"),
        "csize" : 26
}

you see, 54bcc154ed9c800af1d11b47's csize only inc one time, instead of 3 times

1 Answer 1

1

No need to do an $in operation in your query thrice, just increase the field by the specific value you want (in your case it's 3) because the $inc operator accepts positive and negative values.

db.user_info.update(
   { 
       "_id" : ObjectId("54bcc154ed9c800af1d11b47") 
   },
   { 
       "$inc": { "csize": 3 } 
   }
)
Sign up to request clarification or add additional context in comments.

1 Comment

sorry, my example not illustrate my intension clearly, give you another example(I'll edit my question)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.