Upsert Multiple Records with MongoDb

后端 未结 3 2103
广开言路
广开言路 2021-01-05 13:25

I\'m trying to get MongoDB to upsert multiple records with the following query, ultimately using MongoMapper and the Mongo ruby driver.

db.foo.update({event_         


        
3条回答
  •  青春惊慌失措
    2021-01-05 14:30

    This - correctly - will not insert any records with event_id 1 or 2 if they do not already exist

    db.foo.update({event_id: { $in: [1,2]}}, {$inc: {visit:1}}, true, true)

    This is because the objNew part of the query (see http://www.mongodb.org/display/DOCS/Updating#Updating-UpsertswithModifiers) does not have a value for field event_id. As a result, you will need at least X+1 trips to the database, where X is the number of event_ids, to ensure that you insert a record if one does not exist for a particular event_id (the +1 comes from the query above, which increases the visits counter for existing records). To say it in a different way, how does MongoDB know you want to use value 2 for the event_id and not 1? And why not 6?

    W.r.t. batch insertion with ruby, I think it is possible as the following link suggests - although I've only used the Java driver: Batch insert/update using Mongoid?

提交回复
热议问题