MongoDB 与分组不同

MongoDB distinct with grouping

我是 mongo 世界的新人。在某种程度上,我无法真正正确地提出我的问题。但是这里... 所以这是我最好的尝试...

db.t2.insertOne( { animal: "cat", action: "meow"});
db.t2.insertOne( { animal: "cat", action: "stalk"});
db.t2.insertOne( { animal: "cat", action: "claw"});
db.t2.insertOne( { animal: "dog", action: "woof"});
db.t2.insertOne( { animal: "dog", action: "beg"});
db.t2.insertOne( { animal: "fish", action: "swim"});

数据很平淡,对吧?

db.t2.find();
{ _id: ObjectId("61142a398f4cfec27b46e89d"),
  animal: 'cat',
  action: 'meow' }
{ _id: ObjectId("61142a438f4cfec27b46e89e"),
  animal: 'cat',
  action: 'stalk' }
{ _id: ObjectId("61142a4a8f4cfec27b46e89f"),
  animal: 'cat',
  action: 'claw' }
{ _id: ObjectId("61142a7e8f4cfec27b46e8a0"),
  animal: 'dog',
  action: 'woof' }
{ _id: ObjectId("61142a838f4cfec27b46e8a1"),
  animal: 'dog',
  action: 'beg' }
{ _id: ObjectId("61142a918f4cfec27b46e8a2"),
  animal: 'fish',
  action: 'swim' }

我正在寻找一种查询更压缩数据的方法。 像...

[{
"animal":"cat",
"action":["meow", "stalk", "claw"]
},
"animal":"dog",
"action":["woof", "beg"]
},
"animal":"fish",
"action":["swim"]
}]

您可以将它们分组

db.collection.aggregate([
  {
    "$group": {
      "_id": "$animal",
      "actions": {
        "$push": "$action"
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "animal": "$_id",
      "actions": 1
    }
  }
])

Run code here

如果要将数据保存在新表单中,可以执行上述管道,并使用 $out 阶段使用新架构创建新集合。