【问题标题】:MongoDB - Shell Scripting - $in arguments not workingMongoDB - Shell 脚本 - $in 参数不起作用
【发布时间】:2015-06-02 21:36:32
【问题描述】:

我正在使用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
    }})

【问题讨论】:

    标签: mongodb robo3t


    【解决方案1】:

    如果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 运算符将无法使用嵌套数组,因此如果数组的每个元素本身都是一个数组,您可能需要将它们合并到一个更大的数组中。

    【讨论】:

    • 我删除了括号并使用了这个{_id: {$in:arguments}},但我收到了错误"$err" : "Can't canonicalize query: BadValue $in needs an array",
    • @MuratK。 - 因此我们可以推断arguments 实际上不是一个数组。您可以在帖子中添加该变量的值吗?
    • 我更新了。 arguments 是javascript函数的参数。
    • 是的,显然 arguments Object 不是 real 数组。 I had to use this to make it a array var args = Array.prototype.slice.call(arguments);。它现在正在工作。谢谢
    • @MuratK。 - 哦,我明白你的意思了。 argumentsactual arguments object 而不仅仅是一个名为 arguments 的变量 :) 所以是的,你是对的。它看起来和行为都像一个数组,但它实际上不是一个“真正的”数组。 The docs call it"an Array-like object"
    猜你喜欢
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2017-06-21
    • 2013-12-03
    • 1970-01-01
    相关资源
    最近更新 更多