mongodb db.collection.remove用法

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

MongoDB技术学习QQ群: 421431253

 

对于db.collection.remove需要加入加入一个query才能正常运行,否则仅仅运行remove()将会报错,例如:

 

> db.dbdao_stuff.insert({"_id":1,"a":1,"b":1});
WriteResult({ "nInserted" : 1 })
> 
> db.dbdao_stuff.insert({"_id":2,"a":2,"b":3});
WriteResult({ "nInserted" : 1 })
> db.dbdao_stuff.insert({"_id":3,"a":3,"b":6});
WriteResult({ "nInserted" : 1 })
> db.dbdao_stuff.insert({"_id":4,"a":4,"b":10});
WriteResult({ "nInserted" : 1 })
> db.dbdao_stuff.insert({"_id":5,"a":5,"b":15});
WriteResult({ "nInserted" : 1 })
> 
> db.dbdao_stuff.find();
{ "_id" : 1, "a" : 1, "b" : 1 }
{ "_id" : 2, "a" : 2, "b" : 3 }
{ "_id" : 3, "a" : 3, "b" : 6 }
{ "_id" : 4, "a" : 4, "b" : 10 }
{ "_id" : 5, "a" : 5, "b" : 15 }


db.dbdao_stuff.remove();
2015-05-05T21:20:21.275+0800 E QUERY    Error: remove needs a query
    at Error ()
    at DBCollection._parseRemove (src/mongo/shell/collection.js:305:32)
    at DBCollection.remove (src/mongo/shell/collection.js:328:23)
    at (shell):1:16 at src/mongo/shell/collection.js:305


如上语句 仅仅运行 db.dbdao_stuff.remove(); 会报错 Error: remove needs a query
> db.dbdao_stuff.remove({});
WriteResult({ "nRemoved" : 5 })

这时候加入 remove({}); 即可删除所有document

 

 

db.collection.remove有以下2种用法:

 

db.collection.remove(
 <query>,
 <justOne>
)


或者 

db.collection.remove(
 <query>,
 {
 justOne: <boolean>,
 writeConcern: <document>
 }
)

justone=>TRUE 时仅仅删除一条符合条件的document , writeConcern是关于safe write的。

此条目发表在 未分类 分类目录。将固定链接加入收藏夹。

评论功能已关闭。