0

If I wanted to, say, query mongo with something like:

db.someCollection.find({_id: {$in: [1,3,2,4]}})

Could I sort it so that the order it will find/return documents will be in the order listed in the $in list?

What i'm actually thinking of doing is something like this:

db.someCollection.findOne({someField: 'matches', _id: {$in: [1,3,2,4]}}).sort({_id: [1,3,2,4]})

so that it'll return the first document from that list that matches the query.

Is this possible?

B T
  • 57,525
  • 34
  • 189
  • 207
  • @JohnnHK This is not a duplicate question, but the answer you marked as this being a duplicate of HAPPENS to have an answer to my question. Rather than marking my question as a duplicate, please just reference that other answer. – B T Sep 17 '15 at 23:25
  • Yeah, the dupe had kind of goofy title, I updated it to better reflect what all it answers. I'm unclear on why you don't think it's a dupe though. – JohnnyHK Sep 18 '15 at 01:19
  • The first part of the question is somewhat similar to the one mentioned by JhoneyMK. But the solution you seek may be achieved by using the query: db.someCollection.find({someField: 'matches', _id: {$in: [1,3,2,4]}}).sort({_id: 1}).limit(1) instead of using findOne – Arun K Sep 18 '15 at 12:04
  • @JohnnyHK, because the answer to "does the $in clause guarantee order" is no. It doesn't. I know that it doesn't. I'm not asking that. I'm asking *how* you can fix the order - its simply not the same question. Related yes, duplicate no. You changed the question to retroactively make this a duplicate. That's kind of a weird thing to do. – B T Sep 18 '15 at 21:32
  • @ArunK That doesn't do what I want - it sorts by the ids, so they won't come in in the order 1,3,2,4. Rather they would come in the order 1,2,3,4 – B T Sep 18 '15 at 21:33
  • @ B T I don't think so – Arun K Sep 21 '15 at 04:52
  • 1
    Ok well I just tried it, and I was right.. It doesn't return them in the order you list them in the $in operator – B T Sep 21 '15 at 08:49

0 Answers0