【问题标题】:In MongoDb, how to apply sort internal fields present in document?在 MongoDb 中,如何应用文档中存在的排序内部字段?
【发布时间】:2013-03-08 18:18:47
【问题描述】:

我的文档是这样的

{
  field1: somevalue,
   name:xtz


  nested_documents: [ // array of nested document
    { x:"1", y:"2" }, // first nested document
    { x:"2", y:"3" }, // second nested document
    { x:"-1", y:"3" }, // second nested document
    // ...many more nested documents
  ]
}

如何对nested_documents 中的数据进行排序?
预期答案如下:

nested_documents: [ { x:"-1", y:"3" },{ x:"1", y:"2" },{ x:"2", y:"3" }]

【问题讨论】:

  • 这实际上可能在您的客户端代码中比使用聚合框架更快,当然这取决于您的子文档的大小。

标签: mongodb


【解决方案1】:

为此,您必须使用聚合框架

db.test.aggregate([{$unwind:'$nested_documents'},{$sort:{'nested_documents.x': 1}}])

返回

"result" : [
    {
            "_id" : ObjectId("5139ba3dcd4e11c83f4cea12"),
            "field1" : "somevalue",
            "name" : "xtz",
            "nested_documents" : {
                    "x" : "-1",
                    "y" : "3"
            }
    },
    {
            "_id" : ObjectId("5139ba3dcd4e11c83f4cea12"),
            "field1" : "somevalue",
            "name" : "xtz",
            "nested_documents" : {
                    "x" : "1",
                    "y" : "2"
            }
    },
    {
            "_id" : ObjectId("5139ba3dcd4e11c83f4cea12"),
            "field1" : "somevalue",
            "name" : "xtz",
            "nested_documents" : {
                    "x" : "2",
                    "y" : "3"
            }
    }
],
"ok" : 1

希望对你有帮助

【讨论】:

  • 感谢您的回复。但是,我只想要一个对象,其中nested_documents 中的元素已排序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
  • 2015-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多