MongoDB - Shell 脚本 - $in 参数不起作用

MongoDB - Shell Scripting - $in arguments not working

我正在使用 db.system.js.save 在服务器上保存 js 函数。

到目前为止我写了这个脚本

function () {
cursor = db.MyCollection.find({_id: {$in:[arguments]}})
                                             ^ this does not work
        while(cursor.hasNext()){print(cursor.next())};       
}

我用以下参数调用它 findAllDocuments(ObjectId("544a30c80c80d5809180b"),<more objects>);,但它不起作用。

我必须用不同的方式称呼它 arguments 吗?例如,因为 arguments[0] 正在工作。


编辑:为澄清起见,arguments 是 javascript 函数的参数。

findAllDocuments(ObjectId("544a30c80c80d5809180b"),ObjectId("544a30c80c80d5809180b"), <and more objectIds>); 如果我这样使用它,它确实有效,但参数长度可以是可变的。

function () {
cursor = db.MyCollection.find({_id: {$in:[arguments[0],arguments[1]}})
                                             ^ this does work
        while(cursor.hasNext()){print(cursor.next())};       
}

编辑 2:

如何在 $ref 中正确使用 $in?

 cursor = db.MyCollection.find({"trainer" : {
        "$ref" : "Contact",
        "$id" : {$in : [ObjectId("556d901118bfd4901e2a3833")]}
                  ^it executes successfully, but does not find anything
    }})

如果 arguments 已经是一个数组,您不需要将它传递到另一个数组中:

var arguments = [4, 8, 15, 16, 23, 42];
db.col.find({_id: {$in: arguments}})

如果您使用的对象是不是数组,您必须将它们包装在一个数组中:

db.col.find({_id: {$in: [arguments[0], arguments[1], arguments[2]]}})

请记住,您的 $in 运算符将无法处理嵌套数组,因此如果数组中的每个元素本身就是一个数组,您可能需要将它们合并成一个更大的数组。