2

I'm trying to simulate a join in a mongo query so I'm taking the results of my 1st query and then passing it as a $in filter to my 2nd query.

Unfortunately the results of my 1st query returns an array of json objects like so

[ { _id: 4ecd830da046050100000025 },
  { _id: 4ecd84a0a046050100000085 } ]

and the $in filter doesn't return anything because they are json objects instead of a value array. I can manually transform that array but is there a built in method or function that I can use? Also, is there a way I can have mongo return the value array instead? Currently I am calling the find query as such

Likes.find {liker:"Me"}, {_id:1}, {safe:true}

And here is my 2nd query

Post.find {_id:{$in:likes}}

I was hoping for something like

Post.find {_id:{$in:likes._id}}

1 Answer 1

3

Although there is no general solution to your question in the case of $in clauses you can use the result of a distinct operation :

> db.test.save({a:1})
> db.test.save({a:2})
> db.test.save({a:3})
> db.test.save({a:4})

> ids = db.test.distinct("_id", {a:{$gt:2}})
[
        ObjectId("4ece45c2c951f11718678574"),
        ObjectId("4ece45c4c951f11718678575")
]

> db.test.find({_id:{$in:ids}})
{ "_id" : ObjectId("4ece45c2c951f11718678574"), "a" : 3 }
{ "_id" : ObjectId("4ece45c4c951f11718678575"), "a" : 4 }

Hope that helps!

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

4 Comments

cool, that works... how is this technique in terms of performance? Are the distinct queries in mongo realtively fast and quick?
If indexed they are relatively fast yes. Because the query clause of the distinct operation reduces the candidate set significantly it should be relatively close to your original solution. Distinct always requires a full scan of the candidate set so as long as you keep that relatively small you're golden. Good luck.
If the index is a unique index then that operation could be faster by just returning each node in the btree without having to check if they are unique.
Very true. unique=true indexes will help distinct operations significantly.

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.