如何使用聚合 MongoDB 进行 SELECT DISTINCT

问题描述 投票:0回答:1

我正在研究 Mongo 查询,我有一个关于如何使用聚合在 Mongo 查询上进行“选择不同”的问题。我真的很接近完成它了。

我目前的输出:

[
  {
    "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

mongodb mongodb-query aggregate aggregation
1个回答
3
投票

查询

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

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

Playmongo

aggregate(
[{"$group": 
   {"_id": "$user_id",
    "time": {"$first": "$time"},
    "message": {"$first": "$message"}}}])
© www.soinside.com 2019 - 2024. All rights reserved.