【问题标题】:How to perform sort in array of objects in one record in mongoose [duplicate]如何在猫鼬的一条记录中对对象数组进行排序[重复]
【发布时间】:2018-11-28 14:43:30
【问题描述】:

我想通过对 xm_score 排序来获取数据,但它不适用于我的查询。

  query = match.find({ '_id': 'k00012' }).sort('npi.xm_score');

我需要让 npi 中的对象在这个数组中按 xm_score 排序。

我的数据如下,

{
 "term":'k00012',
 "npi" : [ 
    {
        "npi" : "1003000126",
        "xm_score" : 77.1,
        "geo" : [ 
            -75.53091147, 
            40.60619643
        ],
        "state" : "PA",
        "zip" : "18103",
        "specialty" : [ 
            "x010"
        ]
    },
    {
        "npi" : "1003000126",
        "xm_score" : 70.1,
        "geo" : [ 
            -75.53091147, 
            40.60619643
        ],
        "state" : "PA",
        "zip" : "18103",
        "specialty" : [ 
            "x010"
        ]
    }] 
 }

【问题讨论】:

    标签: javascript node.js mongodb mean-stack


    【解决方案1】:

    您可以简单地使用自定义函数来对数组进行排序

    let obj = {
     "term":'k00012',
     "npi" : [ 
        {
            "npi" : "1003000126",
            "xm_score" : 77.1,
            "geo" : [ 
                -75.53091147, 
                40.60619643
            ],
            "state" : "PA",
            "zip" : "18103",
            "specialty" : [ 
                "x010"
            ]
        },
        {
            "npi" : "1003000126",
            "xm_score" : 70.1,
            "geo" : [ 
                -75.53091147, 
                40.60619643
            ],
            "state" : "PA",
            "zip" : "18103",
            "specialty" : [ 
                "x010"
            ]
        }] 
     }
     
    let arr = obj.npi;
    
    arr.sort((a,b) => {
      return a.xm_score - b.xm_score
    })
    
    console.log(arr)

    【讨论】:

      猜你喜欢
      • 2019-06-19
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 2022-01-20
      • 2018-02-01
      • 2019-05-30
      • 2016-10-30
      • 2014-08-04
      相关资源
      最近更新 更多