mongodb - 对嵌套的对象数组进行排序

标签 mongodb sorting nested

我正在寻找一种方法来对嵌套的对象数组进行排序。

这是一个例子:

{
  answers : [
    { name : 'paul',  state : 'RU' },
    { name : 'steve', state : 'US' }, 
    { name : 'mike',  state : 'DE' }, 
    ...
  ]
}

假设现在我想查找 answers 数组中的所有 name,但是如何按升序对它们进行排序?

最佳答案

我会按照您想要的顺序存储它。或者在你把它拉出来之后,在客户端进行排序。

如果两者都不可行,您可以使用 aggregation framework :

> db.test.insert({answers: [
...                 {name: 'paul', state: 'RU'},
...                 {name: 'steve', state: 'US'}, 
...                 {name: 'mike', state: 'DE'}]});
> db.test.insert({answers: [
...                 {name: 'paul', state: 'RU'},
...                 {name: 'steve', state: 'US'}, 
...                 {name: 'xavier', state: 'TX'}]});

db.test.aggregate([
  {$unwind: "$answers"}, 
  {$sort: {"answers.name":1}}, 
  {$group: {_id:"$_id", answers: {$push:"$answers"}}}
]);

产生:

{
  "result" : [
  {
    "_id" : ObjectId("5053b2477d820880c3469364"),
    "answers" : [
      {
        "name" : "paul",
        "state" : "RU"
      },
      {
        "name" : "steve",
        "state" : "US"
      },
      {
        "name" : "xavier",
        "state" : "TX"
      }
    ]
  },
  {
    "_id" : ObjectId("5053af9f7d820880c3469363"),
    "answers" : [
      {
        "name" : "mike",
        "state" : "DE"
      },
      {
        "name" : "paul",
        "state" : "RU"
      },
      {
        "name" : "steve",
        "state" : "US"
      }
    ]
  }
],
  "ok" : 1
}

关于mongodb - 对嵌套的对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12432727/

相关文章:

javascript - MongoError $regex 必须是一个字符串

javascript - SQL 到 Mongo 事务架构

c++ - 排序函数删除数组的一部分,C

dictionary - 如何在 Swift 中访问深层嵌套的字典

mongodb - 环回: Saving one-to-many relations in MongoDB

ruby-on-rails - 何时应嵌入或引用 Mongodb 关联

jquery - jqgrid 客户端排序与服务器端分页 - 数据消失

php - mysql,从 'today'开始对枚举中的天进行排序(滚动)

python - 使用 Python 在迭代创建的嵌套列表中选择上面的级别

html - 想知道我是否可以嵌套输入类型