MongoDB $unset重置某个field

对于已经有值的field,在mongodb中可以使用$unset操作符来重置该field。

http://docs.mongodb.org/manual/reference/operator/update/unset/

具体语法如下:

 

{ $unset: { <field1>: "", ... } }
例如
db.products.update(
 { sku: "unknown" },
 { $unset: { quantity: "", instock: "" } }
)

 

 

具体使用的例子:

db.dbdao_sample.insert({"_id":3,"a":7,"c":[3,4,7,-1,-1]});


> db.dbdao_sample.update({"_id":3},{"$unset" : {"c":""}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.dbdao_sample.find();
{ "_id" : 3, "a" : 7 }


db.dbdao_sample.insert({"_id":4,"a":7,"c":[3,4,7,-1,-1]});


db.dbdao_sample.update({"_id":4},{"$remove" : {"c":""}});

没有$remove这个操作符

> db.dbdao_sample.update({"_id":4},{"c": {"$delete":true }});
2015-05-05T20:38:33.817+0800 E QUERY Error: field names cannot start with $ [$delete]
 at Error (<anonymous>)
 at DBCollection._validateForStorage (src/mongo/shell/collection.js:161:19)
 at DBCollection._validateForStorage (src/mongo/shell/collection.js:165:18)
 at DBCollection._validateUpdateDoc (src/mongo/shell/collection.js:388:14)
 at Object.findOperations.updateOne (src/mongo/shell/bulk_api.js:675:20)
 at DBCollection.update (src/mongo/shell/collection.js:455:22)
 at (shell):1:17 at src/mongo/shell/collection.js:161

> db.dbdao_sample.update({"_id":4},{"c":null});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> 
> db.dbdao_sample.find({"_id":4});
{ "_id" : 4, "c" : null }


> db.dbdao_sample.update({"_id":4},{"c":1});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.dbdao_sample.find({"_id":4});
{ "_id" : 4, "c" : 1 }


Comment

*

沪ICP备14014813号-2

沪公网安备 31010802001379号