How to assign count to a document in a mongodb collection -
i have collection each document has word , unique throughout collection. per requirement, executed script such whenever insert word (document) exists, doesn't inserted.
now, in such cases need add count word whenever try insert same word. can me issue.
you can elegantly combining $inc upsert:true.
when perform update upsert:true option , no document matches update criteria, document inserted collection.
when use $inc , specified field doesn't exist in updated document, gets created , sets value increment by.
so when perform:
db.collection.update( { word:"banana" }, { $inc: { count: 1 } }, { upsert:true } ); two cases possible.
- when document
{ word: "banana", count: 42 }exists, gets changed{ word: "banana", count: 43 }. - when no document
word: "banana"exists, document{ word: "banana", count: 1 }added collection.
by way: when have performance problems, should able speed creating unique index on word. considering have single field never array , query exact equality, can use hashed index amazingly fast larger collections.
Comments
Post a Comment