Vam
Vam

Reputation: 33

MongoDB: Update multiple documents but do NOT upsert

I am trying to update a specific field in few documents but do NOT want to insert that field if it is NOT present in any document. For example if I have following three documents in a collection "test":

{
Name: "abc",
Age: 10,
Hits: 1,
Score: 100
},
{
Name: "def",
Age: 20,
Hits: 1,
Score: 50
},
{
Name: "ghi",
Age: 30,
Score: 100
}

I have tried this command :

 db.test.update({},{$set:{Hits:2}},{multi:true,upsert:false})

here is the output:

    {
    Name: "abc",
    Age: 10,
    Hits: 2,
    Score: 100
    },
    {
    Name: "def",
    Age: 20,
    Hits: 2,
    Score: 50
    },
    {
    Name: "ghi",
    Age: 30,
    Score: 100,
    Hits: 2
   }

My expected output is :

    {
    Name: "abc",
    Age: 10,
    Hits: 2,
    Score: 100
    },
    {
    Name: "def",
    Age: 20,
    Hits: 2,
    Score: 50
    },
    {
    Name: "ghi",
    Age: 30,
    Score: 100
    }

Basically, I am not expecting the Third document with name "ghi" to have the field "Hits". Please let me know your thoughts. Thanks.

Upvotes: 1

Views: 1236

Answers (1)

stalk
stalk

Reputation: 12054

Just add a filter for update:

db.test.update({Hits: {$exists: true}}, {$set: {Hits: 2}}, {multi:true, upsert:false})

Upvotes: 1

Related Questions