gpt4 book ai didi

mongodb在集合中查找不同的文档

转载 作者:行者123 更新时间:2023-12-03 02:12:37 25 4
gpt4 key购买 nike

这是我的消息集合

{
_id: ObjectId("dsdsdsds7878787"),
发件人:“约翰·史密斯”,
接收者:“约翰·多伊”,
msgDateTime: ISODate("2019-09-09T17:44:24.346Z"),
标题:“ Hello World ”,
text: “这是消息正文编号 1”
},{
_id: ObjectId("aaaadsds7878787"),
发件人:“约翰·史密斯”,
接收者:“约翰·多伊”,
msgDateTime: ISODate("2019-09-09T17:44:24.346Z"),
标题:“ Hello World ”,
text: "这是消息正文编号 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这些字段以使事情变得更清晰..

You can view a live demo of this query here..

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"
// }
// ]

关于mongodb在集合中查找不同的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57895910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com