5

我有一个集合 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",


 }]
 }

当我在 mongo shell 中运行以下查询时,我想从具有 name = doc2 的集合 TextDocuments 中删除文档

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')"

文件没有被删除。有什么解决办法吗?

4

1 回答 1

0

你展示的不是自洽的。

如果您确实拥有列出的两个文档,那么您的 remove 命令将删除两个文档,而不是一个。

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 }
于 2014-07-28T05:21:22.913 回答