0

I have a list of people in my database, where each person is one document. I would like to give them standard names (this is just for demo purposes – I don't care who gets which name so long as its unique).

I have an array of names to give them but I am not sure how to do this in Mongo. One simple way would be to just have a cursor and update the documents one by one, but that seems inefficient. Is there a better way to do this?

EDIT:

example db:

{id: 1234, age: 50}
{id: 1235, age: 40}
{id: 1236, age: 30}

Names:

['Bob', 'Jill', 'Gina']

Desired end state:

{id: 1234, age: 50, name: 'Bob'}
{id: 1235, age: 40, name: 'Jill'}
{id: 1236, age: 30, name: 'Gina'}
1
  • Could you post some more information like the collection structure, so that we have more clarity on this question ? Commented Aug 16, 2014 at 12:39

1 Answer 1

1

I'm not sure how you are specifying which names go with which _ids, so I'm going to assume you have a mapping specified in the following form:

> nameMapping
[{ "_id" : 1234, "name" : "Bob" }, { "_id" : 1235, "name" : "Jill" }, { "_id" : 1236, "name" : "Gina" }]

Then a good way to update every doc with a name is to use bulk operations. Bulk operations are supported in the drivers but I'll give the example in the mongo shell with bulk.find.update(), which is available as of MongoDB 2.6.

> var bulk = db.people.initializeUnorderedBulkOp()
> nameMapping.forEach(function(pair) {
    bulk.find( { "_id" : pair._id } ).update( { $set: { "name" : pair.name } } )
})
> bulk.execute()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.