mongodb - MongoDB- 按 id 查找文档,然后用键对其进行分组
问题描述
我的数据结构如下所示:
[
{
"_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那么它应该返回以下内容:
查找具有唯一性_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 具有的类型。
- 空连接结果 => 不同类型,因此它们被过滤掉
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"
]
}
])
推荐阅读
- c++ - Solving this specific C++ diamond problem for Qt classes
- opencv - 计算图像中亮点的数量(python)
- unity3d - Coroutines and triggers
- dart - 如何从某些特定路线中删除持久的底部导航栏?
- rxjs - 为什么 RxJS retryWhen 运算符使用其内部 Observable 完成?
- java - 使用代码输入数据进行反向传播
- javascript - 当用户从确认框中选择否时,如何设置单选按钮的旧值?
- c# - 使用 TFS REST API 导入 GlobalList 时发生错误 TF51635
- javascript - VueJS:属性或方法......未在实例上定义,但在渲染期间引用
- c++ - 如何将 QPrinter 绘图保存为 QPixmap 并将其设置为窗口图标上的 QIcon?