【发布时间】:2021-09-08 20:39:00
【问题描述】:
如何根据 MongoDB 中其他集合的字段从一个集合中查找记录 (例如,集合 A 和集合 B 有一个共同的字段作为用户 ID,就像 SQL 中的主外键概念一样)
就像在 MYSQL 中一样,我可以使用连接查询
SELECT * FROM a
inner join b on a.id=b.id
where id=12
这在 MongoDB 中如何实现?
【问题讨论】:
标签: mongodb
如何根据 MongoDB 中其他集合的字段从一个集合中查找记录 (例如,集合 A 和集合 B 有一个共同的字段作为用户 ID,就像 SQL 中的主外键概念一样)
就像在 MYSQL 中一样,我可以使用连接查询
SELECT * FROM a
inner join b on a.id=b.id
where id=12
这在 MongoDB 中如何实现?
【问题讨论】:
标签: mongodb
由于 MongoDB 是 NoSQL 数据库,因此没有 INNER JOIN,但您仍然可以使用查找 实现你的目标。 在查找中,as 字段指定您希望将数据放在哪里,它可以是新字段,也可以替换现有字段。
只需在最后添加$match即可满足您过滤数据的条件
db.collection(a).aggregate([
{'$match':{id:12}},//Optional if you want or you can leave empty
{'$lookup':{
from:'b',
localField:'id',//fildname of a
foreignField:'id',//field name of b
as:'details' // you can also use id fiels it will replace id with the document
}},
{ $match : { "details" : { $ne : []}}}
])
【讨论】:
您可以在 MongoDB 中通过使用聚合查询来实现这一点,它可用于从两个集合中获取数据。
文档链接:-https://docs.mongodb.com/manual/aggregation/
db.collection(a).aggregate([
{'$match':{id:12}},//Optional if you want or you can leave empty
{'$lookup':{
from:'b',
localField:'id',//fildname of a
foreignField:'id',//field name of b
as:'details'
}}
])
或
如果您使用的是 Node Js 等框架,并且在创建架构时提供了适当的参考,您可以将文档从另一个集合填充到另一个集合
链接:-https://mongoosejs.com/docs/populate.html
【讨论】:
aggregate 返回一个 POJO 对象,因此无法对其进行删除,但您仍然可以通过简单地编写两个查询来实现这一点,首先是聚合,其次是 deleteMany
db.collection(a).aggregate([
{'$match':{id:12}},//Optional if you want or you can leave empty
{'$lookup':{
from:'b',
localField:'id',//fildname of a
foreignField:'id',//field name of b
as:'details' // you can also use id fiels it will replace id with the document
}},
{ $match : { "details" : { $eq : []}}}
])
db.collection(a).deleteMany({id:{$in:[array of ids you get from above query]}})
我不确定它是否有效。
也请兄弟我的回答对您有用或对您有所帮助。
【讨论】: