如何在猫鼬中分组

时间:2020-09-29 16:44:33

标签: node.js mongodb mongoose

比方说,我有一个名称为field的收藏,只有“ Sally”和“ Bob”两个名称存在。我想按此值将结果分组。我目前正在获取结果,然后使用underscore执行group。但是我应该可以使用aggregate来做到这一点。 以下是我的代码

  const names = ['Bob', 'Sally'];
  const docs = Collection.find({name: { $in: names}}, { fields: { name:1, age:1}, sort: { name:-1 } }).fetch();

  //How can I do this part in the query above
  const { Bob, Sally } = _.groupBy(docs, "name");

2 个答案:

答案 0 :(得分:2)

您可以尝试

  • $match您的情况
  • $group by name,并创建称为字段的数组,并推送名称和年龄
  • _id的
  • $sort表示名称
  • $replaceWith替换根目录中的对象,$ arrayToObject将k,v格式转换为对象
const names = ['Bob', 'Sally'];
const docs = Collection.aggregate([
  { $match: { name: { $in: names } } },
  {
    $group: {
      "_id": "$name",
      fields: { 
        $push: { 
          name: "$name",
          age: "$age"
        }
      }
    }
  },
  { $sort: { _id: -1 } },
  {
    $replaceWith: {
      $arrayToObject: [
        [
          {
            k: "$_id",
            v: "$fields"
          }
        ]
      ]
    }
  }
])

Playground

答案 1 :(得分:1)

您可以执行以下操作:

db.collection.aggregate([
  {
    $match: {
      name: {
        $in: names
      }
    }
  },
  {
    $group: {
      "_id": "$name",
      age: {
        $first: "$age"
      }
    }
  },
  {
    $sort: {
      name: -1
    }
  }
])

在这里尝试:MongoPlayground