0

I have a query like below

    query = PhotoLocation.query.filter(photo_location_filters)
    photo_locations = yield query.find()
    id_list = [i.photo_id for i in photo_locations]

    photo_filters = {}
    photo_filters.update({'_id': {'$in': id_list}})
    photo_filters.update({
        "has_images": True,
        "is_hidden": {
            "$ne": True
                }
            })
    query = Photo.query.filter(photo_filters).limit(limit)

I lose the order of id_list after $in query. Is there a way to keep the order of id_list in query below?

tuna
  • 6,211
  • 11
  • 43
  • 63

1 Answers1

0

Not using $in - there's a feature request, SERVER-7528, for it.

If you are using MongoDB version 2.4 or earlier, switching to $or will work:

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

into

db.filters.find({ "$or" : [
    { "_id" : 1 },
    { "_id" : 2 },
    { "_id" : 3 }
] })

This no longer works in MongoDB 2.6.

wdberkeley
  • 11,531
  • 1
  • 28
  • 23
  • 1
    I actually thought I posted a link to a [couple of working solutions](http://stackoverflow.com/questions/22797768/does-mongodbs-in-clause-guarantee-order/22800784#22800784) in the comments of that issue some time back. That would seem better than just copying something from the issue that no longer works. – Neil Lunn Jan 15 '15 at 21:53