2

I don't need to sort the returned documents (objects) but an array each of them based on a nested value.Is it something doable with pymongo.sort()?

Assuming an object is:

{ //document data,
  array : [ {//subdocument data,
             "key" : 185},
             {//subdocument data,
             "key" : 186},
             {...}]
}

I have tried the following which does not work but I search for a simple similar option:

db.col.find().sort('array.key', pymongo.ASCENDING)

or should I do it with python sort?

for location in locations:
    data['array'] = sorted(data['array'], key=lambda x: x['key'])
4

1 回答 1

4

抱歉,目前 Mongo 无法做到这一点。

所以你唯一的办法就是在你的应用程序层中对它进行排序,你正在成功地做到这一点。请注意,如果您总是希望对结果进行排序,则可以通过在 $push 运算符中使用 $sort 来实现。在你的情况下,你会做这样的事情:

db.coll.update(
  { _id : ID },
  { 
     $push: {
       array: {
          $each: [{ key: 13}],
          $sort: { key: 1 }
       }
     }
  })

这样,在任何更新后,您的子文档都会被排序。然后,当您检索它时,您将不需要对其进行排序。

于 2013-11-01T22:14:02.587 回答