gpt4 book ai didi

MongoDB - 按 id 查找文档,然后用键对其进行分组

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


我的数据结构是这样的:

[
{
"_id": "1",
"title": "Yamaha",
"data": "Sed ut perspiciatis",
"type": "Bike"
},
{
"_id": "2",
"title": "Pulsar",
"data": "Quis autem vel eum",
"type": "Bike"
},
{
"_id": "3",
"title": "Tesla Model Y",
"data": "because it is pleasure",
"type": "Car"
},
{
"_id": "4",
"title": "Harley-Davidson",
"data": "praising pain was born",
"type": "Bike"
},
{
"_id": "6",
"title": "Mustang",
"data": "non numquam eius",
"type": "Car"
},
{
"_id": "7",
"title": "BMW",
"data": "Man of Culture",
"type": "Car"
}
]

现在,从前端 用户可以使用他们的唯一_id 从数据库中搜索任何项目 ,像这样:

db.collection.find({_id: "3" })

返回以下内容:

[
{
"_id": "3",
"data": "because it is pleasure",
"title": "Tesla Model Y",
"type": "Car"
}
]

问题部分:

现在,包括上面返回的文件,我还想返回那些匹配 type文件 值。


我的问题意味着;如果用户正在查找带有其特定 _id 的任何文档.让我们假设 3 那么它应该返回以下内容:

用他们的 Unique _id 找到项目 $group type字段

  [{
"_id": "3",
"title": "Tesla Model Y",
"data": "because it is pleasure",
"type": "Car"
}
{
"_id": "6",
"title": "Mustang",
"data": "non numquam eius",
"type": "Car"
},
{
"_id": "7",
"title": "BMW",
"data": "Man of Culture",
"type": "Car"
}]

这可能吗? $group 有可能吗? finding By Id 之后的文档?。我已经尝试了几种方法来做到这一点,但每一种都没有用。对于这个复杂的要求

,任何建议都会有所帮助

:)

最佳答案

查询

  • 自己查找,只加入id=3的类型。
  • 清空连接结果 => 不同类型,因此它们被过滤掉

Test code here

db.collection.aggregate([
{
"$lookup": {
"from": "collection",
"let": {
"type": "$type"
},
"pipeline": [
{
"$match": {
"$expr": {
"$and": [
{
"$eq": [
"$_id",
"3"
]
},
{
"$eq": [
"$$type",
"$type"
]
}
]
}
}
}
],
"as": "joined"
}
},
{
"$match": {
"$expr": {
"$ne": [
"$joined",
[]
]
}
}
},
{
"$unset": [
"joined"
]
}
])

关于MongoDB - 按 id 查找文档,然后用键对其进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69108111/

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