如何使用聚合 MongoDB 创建 SELECT DISTINCT

How to make a SELECT DISTINCT using aggregation MongoDB

我正在研究 Mongo 查询,我有一个关于如何使用聚合对 Mongo 查询进行 'Select Distinct' 的问题。我真的快要完成了。

我当前的输出:

[
  {
    "user_id": "256f5280-fb49-4ad6-b7f5-65c4329d46e0"
  },
  {
    "user_id": "e194d667-d79f-4262-94b1-ecf4561c9418"
  }
]

这是所需的输出:

[
  {
    "time": 1922471890,
    "user_id": "256f5280-fb49-4ad6-b7f5-65c4329d46e0",
    "message": "This is an example of my db (4)"
  },
  {
    "time": 1622471890,
    "user_id": "e194d667-d79f-4262-94b1-ecf4561c9418",
    "message": "This is an example of my db (3)"
  }
]

我当前的聚合查询:

db.collection.aggregate([
  {
    $match: {
      user_id: {
        $regex: ""
      }
    }
  },
  {
    $sort: {
      time: -1
    }
  },
  {
    $group: {
      _id: null,
      user_id: {
        $addToSet: "$user_id",
        
      },
      
    }
  },
  {
    $unwind: "$user_id"
  },
  {
    $project: {
      _id: 0
    }
  },
  {
    $out: "collection"
  }
])

数据集:

[
  {
    "time": 1422471890,
    "user_id": "256f5280-fb49-4ad6-b7f5-65c4329d46e0",
    "message": "This is an example of my db"
  },
  {
    "time": 1622471890,
    "user_id": "256f5280-fb49-4ad6-b7f5-65c4329d46e0",
    "message": "This is an example of my db (1)"
  },
  {
    "time": 1622471890,
    "user_id": "256f5280-fb49-4ad6-b7f5-65c4329d46e0",
    "message": "This is an example of my db (2)"
  },
  {
    "time": 1622471890,
    "user_id": "e194d667-d79f-4262-94b1-ecf4561c9418",
    "message": "This is an example of my db (3)"
  },
  {
    "time": 1922471890,
    "user_id": "256f5280-fb49-4ad6-b7f5-65c4329d46e0",
    "message": "This is an example of my db (4)"
  }
]

当我获取所有数据时,我不希望重复 user_id,所以我只需要从 id 中找到的第一个信息。

此 Mongo 查询的 Mongo Playground

查询

  • $user_id 分组以仅包含不同的用户
  • 取其他字段重复值的$first

*您可以根据需要添加排序或匹配阶段

Playmongo

aggregate(
[{"$group": 
   {"_id": "$user_id",
    "time": {"$first": "$time"},
    "message": {"$first": "$message"}}}])