Domanda

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?

È stato utile?

Soluzione

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})

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top