我有一个集合 TextDocuments
/* 0 */
{
name:"doc2",
pages:[{
pageNumber:"1",
text:"This is first page text",
},{
pageNumber:"2",
text:"This is second page text",
},{
pageNumber:"3",
text:"This is third page text",
}]
}
/* 1 */
{
name:"doc2",
pages:[{
pageNumber:"1",
text:"This is first page text",
},{
pageNumber:"2",
text:"This is second page text",
},{
pageNumber:"3",
text:"This is third page text",
}]
}
我想从名称为 doc2 的 TextDocuments 集合中删除文档 当我在 mongo shell 中运行以下查询时
rohitkumar@ubuntuhost:~$ mongo
> use mydb
switched to db mydb
> db.TextDocuments.remove({"name":"doc2"})
WriteResult({ "nRemoved" : 1 })
>
但在第二种情况下 我创建了一个 shell 脚本
//File name collectionRemove.js
var db = connect("localhost:27017/mydb");
var names= ["doc1","doc2"];
for(i=0;i<names.length;i++){
db['TextDocuments'].remove({"name":names[i]});
}
当使用以下命令从 mongo shell 执行时
rohitkumar@ubuntuhost:~$mongo mydb --eval "load('collectionRemove.js')"
文件没有被删除。有什么解决办法吗?
最佳答案
你展示的内容不是自洽的。
如果您实际上有您列出的两个文档,那么您的删除命令将删除两个文档,而不是一个。
db.TextDocuments.insert({ name:"doc2", pages:[{ pageNumber:"1", text:"This is first page text", },{ pageNumber:"2", text:"This is second page text", },{ pageNumber:"3", text:"This is third page text", }]})
WriteResult({ "nInserted" : 1 })
db.TextDocuments.insert({ name:"doc2", pages:[{ pageNumber:"1", text:"This is first page text", },{ pageNumber:"2", text:"This is second page text", },{ pageNumber:"3", text:"This is third page text", }]})
WriteResult({ "nInserted" : 1 })
db.TextDocuments.remove({"name":"doc2"})
WriteResult({ "nRemoved" : 2 })
现在让我们试试你的 JS 文件内容(当然是在重新插入相同的两个文档之后):
var db = connect("localhost:27017/so"); 连接到:localhost:27017/so var names= ["doc1","doc2"]; 对于(我= 0;我
再次,在第二次通过循环时删除了两个文档(因为在您给出的小示例中实际上没有“doc1”名称值。
现在让我们插入一个带有“doc1”的文档和一个带有“doc2”的文档,并尝试使用一个稍微更能说明问题的脚本版本:
db.TextDocuments.insert({ name:"doc1", pages:[{ pageNumber:"1", text:"This is first page text", },{ pageNumber:"2", text:"This is second page text", },{ pageNumber:"3", text:"This is third page text", }]})
WriteResult({ "nInserted" : 1 })
db.TextDocuments.insert({ name:"doc2", pages:[{ pageNumber:"1", text:"This is first page text", },{ pageNumber:"2", text:"This is second page text", },{ pageNumber:"3", text:"This is third page text", }]})
WriteResult({ "nInserted" : 1 })
var db = connect("localhost:27017/so");
connecting to: localhost:27017/so
for(i=0;i<names.length;i++){ print("Removing name " + names[i]); printjson(db['TextDocuments'].remove({"name":names[i]})); }
Removing name doc1
{ "nRemoved" : 1 }
Removing name doc2
{ "nRemoved" : 1 }
关于mongodb - db.collection.remove() 不删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23516279/