How to continue insertion after duplicate key error using PyMongo

You need to use insert_many method and set the ordered option to False. db_stock.insert_many(<list of documents>) As mentioned in the ordered option documentation: ordered (optional): If True (the default) documents will be inserted on the server serially, in the order provided. If an error occurs all remaining inserts are aborted. If False, documents will be … Read more

Update embedded object inside array inside array in MongoDB

You can only use the $ positional operator for single-level arrays. In your case, you have a nested array (heros is an array, and within that each hero has a spells array). If you know the indexes of the arrays, you can use explicit indexes when doing an update, like: > db.test.update({“heros.nickname”:”test”, “heros.spells.spell_id”:1}, {$set:{“heros.0.spells.1.level”:3}});

How to toggle a boolean field in one document with atomic operation?

Right now, I don’t think it’s possible to do this with one operation. The bitwise operators (http://www.mongodb.org/display/DOCS/Updating#Updating-%24bit) don’t have a ‘$xor’ yet although I’ve a patch for it. Right now the workaround I think think of is by always using ‘$inc’: cl.update( { “_id”: …}, { ‘$inc’ : { ‘field’ : 1 } } ); … Read more

Mongodb aggregation pipeline how to limit a group push

Suppose the bottom left coordinates and the upper right coordinates are respectively [0, 0] and [100, 100]. From MongoDB 3.2 you can use the $slice operator to return a subset of an array which is what you want. db.collection.aggregate([ { “$match”: { “loc”: { “$geoWithin”: { “$box”: [ [0, 0], [100, 100] ] } }} … Read more

How do I rename fields when performing search/projection in MongoDB?

So basically using .aggregate() instead of .find(): db.tweets.aggregate([ { “$project”: { “_id”: 0, “coords”: “$level1.level2.coordinates” }} ]) And that gives you the result that you want. MongoDB 2.6 and above versions return a “cursor” just like find does. See $project and other aggregation framework operators for more details. For most cases you should simply rename … Read more