mercyweeps
mercyweeps

Reputation: 13

MongoDB search using $in array not working

I'm using MongoDB shell version: 2.4.8, and would simply like to know why a nested array search doesn't work quite as expected.

Assume we have 2 document collections, (a) Users:

{
    "_id" : ObjectId("u1"),
    "username" : "user1",
    "org_ids" : [ 
        ObjectId("o1"), 
        ObjectId("o2")
    ]
}
{
    "_id" : ObjectId("u2"),
    "username" : "user2",
    "org_ids" : [ 
        ObjectId("o1") 
    ]
}

and (b) Organisations:

{
    "_id" : ObjectId("o1"),
    "name" : "Org 1"
}
{
    "_id" : "ObjectId("o2"),
    "name" : "Org 2"
}

Collections have indexes defined for

Users._id, Users.org_id, Organisations._id

I would like to find all Organisations a specific user is a member of.

I've tried this:

> myUser = db.Users.find( { _id: ObjectId("u1") })
> db.Organisations.find( { _id : { $in : [myUser.org_ids] }})

yet it yields nothing as a result. I've also tried this:

> myUser = db.Users.find( { _id: ObjectId("u1") }) 
> db.Organisations.find( { _id : { $in : myUser.org_ids }})

but it outputs the error:

error: { "$err" : "invalid query", "code" : 12580 }

(which basically says you need to pass $in an array) ... but that's what I thought I was doing originally ? baffled.

Any ideas what I'm doing wrong?

Upvotes: 1

Views: 243

Answers (1)

Ionică Bizău
Ionică Bizău

Reputation: 113475

db.collection.find() returns a cursor - according to documentation. Then myUser.org_ids is undefined, but $in field must be an array. Let's see the solution!


_id is unique in a collection. So you can do findOne:

myUser = db.Users.findOne( { _id: ObjectId("u1") })
db.Organisations.find( { _id : { $in : myUser.org_ids }})

If you are searching for a non-unique field you can use toArray:

myUsers = db.Users.find( { username: /^user/ }).toArray()

Then myUsers will be an array of objects matching to the query.

Upvotes: 2

Related Questions