2

I need help incrementing value of all keys in participants without having to know name of the keys inside of it.

> db.conversations.findOne()

{
"_id" : ObjectId("4faf74b238ba278704000000"),
"participants" : {
    "4f81eab338ba27c011000001" : NumberLong(2),
    "4f78497938ba27bf11000002" : NumberLong(2)
}
}

I've tried with something like

$mongodb->conversations->update(array('_id' => new \MongoId($objectId)), array('$inc' => array('participants' => 1)));

to no avail...

2 Answers 2

2

You need to redesign your schema. It is never a good idea to have "random key names". Even though MongoDB is schemaless, it still means you need to have defined key names. You should change your schema to:

{
    "_id" : ObjectId("4faf74b238ba278704000000"),
    "participants" : [
        { _id: "4f81eab338ba27c011000001", count: NumberLong(2) },
        { _id: "4f78497938ba27bf11000002", count: NumberLong(2) }
    ]
}

Sadly, even with that, you can't update all embedded counts in one command. There is currently an open feature request for that: https://jira.mongodb.org/browse/SERVER-1243

In order to still update everything, you should:

  • query the document
  • update all the counts on the client side
  • store the document again

In order to prevent race conditions with that, have a look at "Compare and Swap" and following paragraphs.

2
  • Ok, I've updated schema and all methods according to your example, however when doing a update by running your code above error message "can't append to array using string field name [count]" is displayed.
    – Sputnik
    May 13, 2012 at 11:50
  • You're right. There is a Jira ticket for this: jira.mongodb.org/browse/SERVER-1243 Please vote for it! I've updated my answer.
    – Derick
    May 14, 2012 at 13:01
0

It is not possible to update all nested elements in one single move in current version of MongoDB. So I can advice to use "foreach {}".

Read realted topic: How to Update Multiple Array Elements in mongodb

I hope this feature will be implemented in next version.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.