【问题标题】:How do I find records from one collection based on field of other collection in MongoDB如何根据MongoDB中其他集合的字段从一个集合中查找记录
【发布时间】: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


    【解决方案1】:

    由于 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 新手,在构建查询时遇到问题。
    • 您想从数据库中删除一些文档还是只从过滤后的查询结果中删除文档?
    • 我的最终目标是 - 我有两个集合,分别是 A 和 B,有一个公共字段说 id,我想从集合 A 中删除集合 B 中没有 id 的记录
    【解决方案2】:

    您可以在 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

    【讨论】:

    • 感谢您的回复...但它会创建一个名为 details 的额外字段..不会过滤掉数据..您能提供其他查询吗?
    【解决方案3】:

    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]}})
    

    我不确定它是否有效。
    也请兄弟我的回答对您有用或对您有所帮助。

    【讨论】:

    • 好的,谢谢!我是 stackoverflow 的新手,因此我的投票没有显示!
    • 没问题的兄弟。我希望我能帮到你。
    • 是的兄弟,它确实有帮助
    猜你喜欢
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 2015-04-06
    • 2018-12-26
    • 2021-10-27
    相关资源
    最近更新 更多