Black
Black

Reputation: 5367

mongodb: add an attribute to a subdocument

Given a collection of Users:

db.users.insertMany(
[
 {
   _id: 1,
   name: "sue",
   points: [
      { points: 85, bonus: 20 },
      { points: 85, bonus: 10 }
   ]
 },
 {
   _id: 2,
   name: "bob",
   points: [
      { points: 85, bonus: 20 },
      { points: 64, bonus: 12 }
   ]
 }]);

How do I add an attribute bonus_raw in every points, with a copy of the value of bonus value? I tried:

db.getCollection('users').update({ },
    {$set:{ 'points.$.bonus_raw' : 'points.$.bonus' }}, false, true)

but I get:

The positional operator did not find the match needed from the query. Unexpanded update: points.$.bonus_raw

Upvotes: 0

Views: 99

Answers (1)

Tarush Arora
Tarush Arora

Reputation: 576

Updating multiple items in an array is not possible as of now in MongoDB.

To get this done, you will have to query the document, loop over all of your nested documents, and then save it back to MongoDB.

In your case, this can help:-

db.users.find({points: { $exists: true } }).forEach(function (doc){
    doc.points.forEach(function (points) {
        points.bonus_raw = points.bonus;
    });
    db.users.save(doc)
});

Also, take care of race conditions while doing an update in this way. See this

Upvotes: 1

Related Questions