本文介绍了在MongoDb中,如何应用文档中存在的排序内部字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档看起来像这样

{
  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中存在的数据进行排序?
预期的答案如下所示:

How one can sort the data present in nested_documents?
Expected answer is shown below:

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

推荐答案

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

To do this you would have to use the aggregation framework

这将返回

"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

希望这会有所帮助

这篇关于在MongoDb中,如何应用文档中存在的排序内部字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 05:41