mongodb - 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()
我怎样才能做到这一点?
解决方案
您应该可以为此使用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"
// }
// ]
推荐阅读
- sql - oracle中sql比plsql快吗
- css - 将 JSON 配置文件导入到 styles.css
- javascript - $ 和 document 已定义,但 $(document) 未定义
- pointers - 布尔值的无效数据
- oracle-sqldeveloper - Oracle SQL 开发人员在编辑代码时滞后
- java - 是否有向实体添加动态 where 子句以动态过滤该实体的任何查询结果?
- mysql - JSON 中第 22 位的意外字符串
- ruby-on-rails - 错误在设计注册时未正确显示
- flutter - 如何获得颤振图像的尺寸?
- javascript - 如何解决未捕获的 typeError - 无法读取 null 的属性“addEventListener”