您可以使用upsert這將做你想要什麼:
db.mobile.update({ '_id':{'mobileno': '2301658146', 'provider': 'Airtel'}}, {'name' : 'abc'}, {upsert:true})
db.mobile.update({ '_id':{'mobileno': '2301658146', 'provider': 'docomo'}}, {'name' : 'abc'}, {upsert:true})
結果:
{ "_id" : { "mobileno" : "2301658146", "provider" : "Airtel" }, "name" : "abc" }
{ "_id" : { "mobileno" : "2301658146", "provider" : "docomo" }, "name" : "abc" }
與同_id.mobileno
和_id.provider
再次運行相同的命令將更新現有的文件:
db.mobile.update({ '_id':{'mobileno': '2301658146', 'provider': 'Airtel'}}, {'name' : 'xyz'}, {upsert:true})
結果:
{ "_id" : { "mobileno" : "2301658146", "provider" : "Airtel" }, "name" : "xyz" }
{ "_id" : { "mobileno" : "2301658146", "provider" : "docomo" }, "name" : "abc" }