Tomasz Lenarcik
Tomasz Lenarcik

Reputation: 4890

Mongo array update or push in one query

Let's assume we have mongo collection containing documents of the following shape:

 {
   _id: '1234',
   letters: ['a', 'b', 'c', 'd'],
 }

but sometimes the letters field may be null.

I am wondering if it is possible to achieve the following in a SINGLE query

Of course, the simplest possible idea does not work

db.collection.update({_id: '...'}, {$set:{'letters.0':'x'}});

because if the letters field was not yet set the result of the above operation will be:

{
  // ...
  letters: {
    '0': 'x'
  }
}

Is there some way to tell mongo that my intention is to create an array, not an object?

Upvotes: 1

Views: 6151

Answers (2)

yuc
yuc

Reputation: 508

If you want to update the first one in the array

pop out the old first one

db.collection.update({_id:xx}, {$pop:{letters : -1}})

Then push to the first one

db.collection.update({_id:xx}, {$push:{letters : {$each:['first one'], $position:0}}})

Upvotes: 0

You can use the $push operator, or the $addToSet if you care for duplicates on the array.

Your query will look like this:

db.collection.update({_id: '...'}, {$push:{'letters':'x'}});
db.collection.update({_id: '...'}, {$addToSet:{'letters':'x'}});

Upvotes: 3

Related Questions