如何在mongo中按任意列表对对象数组进行排序 [英] how to sort array of objects by arbitrary list in mongo

查看:161
本文介绍了如何在mongo中按任意列表对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种通过任意列表对对象数组进行排序的方法.假设我有这个对象数组.

I was looking for a way to sort array of object by an arbitrary list. Lets assume I have this array of objects.

[
  {
   "_id": "4JEEuhNIae",
   "category": "grocery"
  },
  {
   "_id": "4JW7miNITl",
   "category": "food"
  },
  {
   "_id": "4Je4kmrrbZ",
   "category": "coffee"
  },
  {
   "_id": "4JgAh3N86x",
   "category": "coffee"
  }
]

这是我想用作排序条件的数组.带有food的记录应该首先出现,然后是coffeegrocery.

This is the array that I would like to use as sorting criteria. Records with foodshould come first, then coffeeand grocery.

['food','coffee','grocery']

结果应为:

[
  {
   "_id": "4JW7miNITl",
   "category": "food"
  },
  {
   "_id": "4Je4kmrrbZ",
   "category": "coffee"
  },
  {
   "_id": "4JgAh3N86x",
   "category": "coffee"
  },
  {
   "_id": "4JEEuhNIae",
   "category": "grocery"
  },
]

如何使用mongoose在mongodb上进行这种类型的排序?我真的不想在获取数据后对代码进行任何操作.

How can I do this type of sorting on mongodb by using mongoose? I really don't want to make any operations on the code after fetching data.

推荐答案

您可以尝试使用本机JavaScript

You could try running a custom comparator function with the native JavaScript sort() method on the array returned from the cursor.toArray() method:

var order = ["food", "coffee", "grocery"];
var docs = db.collection.find().toArray().sort(function(a, b) { 
    return order.indexOf(a.category) - order.indexOf(b.category);
});
printjson(docs);

示例输出

[
    {
        "_id" : "4JW7miNITl",
        "category" : "food"
    },
    {
        "_id" : "4Je4kmrrbZ",
        "category" : "coffee"
    },
    {
        "_id" : "4JgAh3N86x",
        "category" : "coffee"
    },
    {
        "_id" : "4JEEuhNIae",
        "category" : "grocery"
    }
]


使用新的MongoDB 3.4版本,您应该能够利用本机MongoDB运算符


With the new MongoDB 3.4 version, you should be able to leverage the use of the native MongoDB operators $addFields and $indexOfArray in the aggregation framework.

  • The $addFields pipeline step allows you to $project new fields to existing documents without knowing all the other existing fields.
  • The $indexOfArray expression returns position of particular element in a given array.

因此,完全可以尝试以下聚合操作(使用MongoDB 3.4):

So putting that altogether you could try the following aggregate operation (with MongoDB 3.4):

var order = ["food", "coffee", "grocery"],
    projection = { 
        "$addFields" : { 
            "__order" : { "$indexOfArray" : [ order, "$category" ] } 
        } 
    },
    sort = { "$sort" : { "__order" : 1 } };
db.collection.aggregate([ projection, sort]);

这篇关于如何在mongo中按任意列表对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆