转载

MongoDB $unset重置某个field

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

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

dbDao 百度贴吧:http://tieba.baidu.com/dbdao

MongoDB技术学习QQ群: 421431253

具体语法如下:

{ $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 }

相关文章 | Related posts:

  1. MongoDB _id Key的一些信息 关于 mongodb _id key: _id key可以用户分配,也可以由mongodb自动分配,一般采用自 […]...
  2. MongoDB db.collection.remove()方法 mongodb中删除document采用remove方法, http://docs.mongodb.org/m […]...
  3. mongodb $all操作符 $all操作符帮助选择collection中field是array类型的,且该array包含所有指定的元素的d […]...
  4. 了解db.collection.find() db.collection.find()可能是mongodb中最常用的方法之一了,其定义为db.collect […]...
  5. 11g中如何禁用自动统计信息收集作业 11g中如何禁用自动统计信息收集作业? 因为11g中auto stats gather job被集成到auto […]...
  6. MongoDB 获得参数和命令行启动选项 dbDao 百度贴吧:http://tieba.baidu.com/dbdao MongoDB技术学习QQ群: […]...
正文到此结束
Loading...