sijo vijayan
sijo vijayan

Reputation: 1710

$each not working in mongodb

I would like to add new data into a child element of a field in mongodb using update query with $push and $each, But it directly insert the whole part of each operator. please help me to fix it. My query given below.

> db.Groups.insert({ "_id" : ObjectId("55b54aa4e2aa83f1f123a1a2"), "_creator" : ObjectId("55b2932cb57f47c0be6f071f"), "_messages" : ["hi"], "_inactive" : [ ], "_active" : [ Obje

> .Groups.update({ "_id" : ObjectId("55b54aa4e2aa83f1f123a1a2")},{$push: {_active : { $each: [ ObjectId("55b2932cb57f47c0be6f072f"), ObjectId("55b2932cb57f47c0be6f073f") ]}}});

Result after running these queries

{ "__v" : 39, "_active" : [     ObjectId("55b2932cb57f47c0be6f071f"),   ObjectId("55b28b203a6b52e9b90e3cd4"),   {   "$each" : [     ObjectId("55b2932cb57f47c0be6f072f"),   ObjectId("55b2932cb57f47c0be6f073f") ] } ], "_creator" : ObjectId("55b2932cb57f47c0be6f071f"), "_id" : ObjectId("55b54aa4e2aa83f1f123a1a2"), "_inactive" : [ ], "_messages" : [ "hi" ] }

Expected result

{ "__v" : 39, "_active" : [     ObjectId("55b2932cb57f47c0be6f071f"),   ObjectId("55b28b203a6b52e9b90e3cd4"), ObjectId("55b2932cb57f47c0be6f072f"),     ObjectId("55b2932cb57f47c0be6f073f") ], "_creator" : ObjectId("55b2932cb57f47c0be6f071f"), "_id" : ObjectId("55b54aa4e2aa83f1f123a1a2"), "_inactive" : [ ], "_messages" : [ "hi" ] }

Upvotes: 0

Views: 294

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50416

The version of MongoDB here must be a very old version, and now confirmed as 2.0.4. This should even error in 2.2.x versions due to it interpretting the $each as a field and rejecting it due to the reserved $ in the field name.

Use at least MongoDB 2.4 if you intend to use $each, otherwise there is $pushAll, which is now considered deprecated. The only difference being between 2.4 and 2.6 is that earlier than 2.6 you need to combine this with the $sort modifer as well.

Upvotes: 2

Related Questions