1

I am using db.system.js.save to save js functions on the server.

I wrote this script so far

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

I am calling it with the following argument findAllDocuments(ObjectId("544a30c80c80d5809180b"),<more objects>);, but it is not working.

Do I have to call it arguments differently? Because arguments[0] is working for example.


Edit: For clarification arguments are the parameters of the javascript function.

findAllDocuments(ObjectId("544a30c80c80d5809180b"),ObjectId("544a30c80c80d5809180b"), <and more objectIds>); If I use it like this it does work, but the arguments length can be variable.

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

EDIT 2:

How can I use the $in correctly in $ref?

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

1 Answer 1

2

If arguments is already an array you don't need to pass it inside another array:

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

If the objects you are working with are not arrays you have to wrap them within an array:

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

Keep in mind that your $in operator won't be able to work with nested arrays so if each element of your array is an array itself you might need to merge them together into one larger array.

Sign up to request clarification or add additional context in comments.

9 Comments

I removed the brackets and went with this {_id: {$in:arguments}}, but I am getting the error "$err" : "Can't canonicalize query: BadValue $in needs an array",
@MuratK. - so from this we can deduce that arguments is not in fact an array. Can you add to your post the value of that variable?
I updated it. The arguments are the parameters of the javascript function.
Yes it was, apparently arguments Object is not a real array. I had to use this to make it a array var args = Array.prototype.slice.call(arguments);. It is now working. Thanks
@MuratK. - ohhhhh I see what you mean now. arguments was the actual arguments object and not just a variable called arguments :) So yes, you are correct. It looks and behaves like an array but it's not actually a "real" array. The docs call it "an Array-like object"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.