我有一个集合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')"
文档未被删除。任何解决方案?
答案 0 :(得分:0)
你展示的不是自我一致的。
如果你确实有你列出的两个文件,那么你的删除命令会删除两个文件,而不是一个。
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(&#34; localhost:27017 / so&#34;); 连接到:localhost:27017 / so var names = [&#34; doc1&#34;,&#34; doc2&#34;]; 对于(I = 0;我
同样,第二次通过循环删除了两个文档(因为你实际上没有&#34; doc1&#34;你给出的小例子中的名称值。
现在让我们使用&#34; doc1&#34;插入一个文档。和#34; doc2&#34;并尝试稍微更具启发性的脚本版本:
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 }