MongoDB- 根据id查找文档,然后按键分组
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" }]
这是可能的吗?在按ID查找
之后$group
文档是可能的吗?我已经尝试了几种方法,但它们每一个都没有用。任何建议都将有助于这个复杂的需求
🙂
admin 更改状态以发布 2023年5月21日
你基本上在混合两个独立的查询:
- 通过ID获取一个项目-返回单个项目
- 获取具有与第一个项目类型相同的类型的项目列表-返回项目列表
由于查询的差异,没有非常直接的方法来实现。当然,你可以使用$aggregate来实现,但根据逻辑,你仍然需要从数据库中查询相当多的内容,并且你需要深入挖掘才能对其进行适当的优化。
只要你不查询数千万条记录,出于简单起见,我建议你一个接一个地进行这两个查询。
查询
- 与本身查找,仅与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" ] } ])