首页 > 解决方案 > mongodb在集合中查找不同的文档

问题描述

这是我的留言集

{ _id: ObjectId("dsdsdsds7878787"), sender: "John Smith", reciever: "John Doe", msgDateTime: ISODate("2019-09-09T17:44:24.346Z"), title: "hello world", text: "this is message body number 1" },{ _id: ObjectId("aaaadsds7878787"), sender: "John Smith", reciever: "John Doe", msgDateTime: ISODate("2019-09-09T17:44:24.346Z"), title: "hello world", text: "this is message body number 2", }

当我使用下面的查询时,它会显示(N)个文档,但我只需要在 MYSQL 中显示一个像 DISTINCT 这样的文档,我不想重复它 n 次。

db.message.find({sender:"John Smith", reciever: "John Doe", title: "hello world"}, {_id:0, sender:1, reciever:1, title:1}).pretty()

我怎样才能做到这一点?

标签: mongodbmongodb-query

解决方案


您应该可以为此使用aggregate..您可以$group通过类似的字段,然后$project这些字段使事情变得更清洁..

您可以在此处查看此查询的实时演示。

db.collection.aggregate([
  {
    $match: {
      "sender": "John Smith",
      "reciever": "John Doe",
      "title": "hello world"
    }
  },
  {
    $group: {
      _id: {
        "sender": "$sender",
        "reciever": "$reciever",
        "title": "$title"
      }
    }
  },
  {
    $project: {
      _id: 0,
      "reciever": "$_id.reciever",
      "sender": "$_id.sender",
      "title": "$_id.title"
    }
  }
])

// OUTPUT:
// [
//   {
//     "reciever": "John Doe",
//     "sender": "John Smith",
//     "title": "hello world"
//   }
// ]

推荐阅读