sajith
sajith

Reputation: 2702

MongoDb pymongo how to increment multiple documents

I have a document as following in MongoDb

{ 
   "_id" : ObjectId("53490030cf3b942d63cfbc7b"),
   "dt" : ISODate("2014-04-12T00:00:00Z"),
   "uId" : "abdc123", "count" : 12 
 }

I have a list of uIds as ["abdc123","abc","cde","efg"]

I need to increment count by one for each uId matching todays date .if any uId has no value in todays "dt" then update should add a new doc for each UIDS with count 1

My query in python follows

client.Mydb.mycoll.update(
    {
       "uId":{"$in":["abdc123","abc","cde","efg"]},
       "dt":datetime(y,m,d)
    },
    {"$inc":{"count":1}},
    upsert=True,
    multi=True
)

but output is not as expected,it create only one document with count 1

suggest me the correct query in pymongo

Update:for incrementing an already existing value the above code works,but no new document is creating if "uId" and "dt" not in collection

Upvotes: 3

Views: 2091

Answers (2)

Niyasim
Niyasim

Reputation: 76

For doing the record update as mentioned you need to work with pymongo.bulk.BulkUpsertOperation as following

from pymongo.bulk import BulkUpsertOperation
bulk=clientConn.db.table.initialize_ordered_bulk_op()

for i in someList:
    bulk.find({'uid':i,"dt":datetime(y,m,d)}).upsert().update({'$inc': {'count': 1}})
res=bulk.execute()

hope this will help.

Upvotes: 6

Lalit Agarwal
Lalit Agarwal

Reputation: 2354

I think you will have to do something like below to make it work..

["abdc123","abc","cde","efg"] { ///lopp all of them
  client.Mydb.mycoll.update({
    "uId": <loop-variable>, // for each value .. eg. "abc123" ... 
    "dt":datetime(y,m,d)},{"$inc":{"count":1}
    },
    upsert=True,
    multi=True
   )
}

Upvotes: 0

Related Questions