4

My command like this:

db.item.remove()    
db.item.update({_id:{$in:['A1','A2']}},{$inc:{count:1}},{multi: true, upsert: true})

my desired result should be

db.item.find() -->
{_id: 'A1', count: 1}
{_id: 'A2', count: 1}

but in fact it is:

{_id: ObjectId(xxx), count: 1}
{_id: ObjectId(xxx), count: 1}

seems like Upsert cannot automatic use the val in the query arrary as the _id of new document, is there a way to get my purpose?

lonevan
  • 65
  • 1
  • 7

2 Answers2

2

You can only upsert one document at a time, so you need to split it into two update calls.

db.item.update({_id: 'A1'},{$inc:{count:1}},{upsert: true})
db.item.update({_id: 'A2'},{$inc:{count:1}},{upsert: true})
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • Split into a multi update calls is a solution, but I don't think it is an efficient way. Is it possible to execute in one command? – lonevan Dec 21 '12 at 06:27
  • 1
    No, that's pretty much what he's saying. With the exception of bulk inserts all other writes require a call per write. – Remon van Vliet Dec 21 '12 at 14:50
0

It depends on whether the documents already exist. If this do not then you could always use BatchInsert which in the latest MongoDB has been delegated to the insert function: http://docs.mongodb.org/manual/applications/create/#insert

If you pass an array of documents to the insert() method, the insert() performs a bulk insert into a collection.

So that copuld be one way to go, however your documents are so small the only real benefit you will get from doing this all in one command is that you get one round trip but you must send all your data over the wire at the same time.

I should also note that batch inserting changes when under sharding and there are certain considerations you should probably take into account: http://docs.mongodb.org/manual/administration/sharding/#strategies-for-bulk-inserts-in-sharded-clusters due to the performance impact bulk inserts can have on your system.

However if the documents might already exist the only realy way atm is to do the command manually like @JohnnyHK says. I don't think any of MongoDBs other tools like mongoimport will help you here since those too do batch inserts.

Sammaye
  • 43,242
  • 7
  • 104
  • 146