Querying mongodb keeping the order, using the $in operator
I have a list of urls (resources), and a list of views for each resource, all of them are
stored into a mongodb database. In other words, a resource
has many associa开发者_运维知识库ted views
.
Both resources and views contain a field url
, which I'm using to identify the website the resource and the view is about.
I have a list of urls in a var urls
, and I want to return, for each of them, in the same order urls are, only one of the views that is associated with this url.
So there is two criterion that are interesting for me:
- Query using the $in operator, keeping the order of the results regarding the list I passed.
- Only returning one item for each key in the $in list.
Of course, I can iterate in my code and do something like this (in python):
views = []
for url in urls:
views.append(db.views.find_one({"url": url}))
I don't know how the $in
operator exactly behaves and if it can solve my problem, but I'm afraid it will not keep the order I'm interested in. Maybe can I sort the results after querying?
But this means making N queries for N urls which doesn't seems optimized at all. Is there a way to avoid this?
Unfortunately this is not currently possible. There is no order guarantee for $in (verify with db.test.save({a:1}); db.test.save({a:2}); db.test.find({a:{$in:[2,1]}})
) and currently you can only sort on fields and not fixed ordered sets of values.
精彩评论