首页 > 解决方案 > 如何在mongodb中将集合A中的字符串与集合B匹配

问题描述

我有收藏 A

-> {"_id": .... , "data":"demon"}
-> {"_id": .... , "data":"god"}

集合 B 作为

-> {"_id": .... , "title": "Book A", "description": "this book is about a demon."}
-> {"_id": .... , "title": "Book B", "description": "this book is about a god from Greek."}
-> {"_id": .... , "title": "Book C", "description": "this book is about a dog."}

我想从集合 B 中提取文档,其中描述不包含集合 A 的“数据”字段中的任何文本。

在普通 JS 中,我想在 Mongo Query 中使用以下内容

collectionA.filter( x => { return !collectionB.some(y => x.description.includes(y.data)});

如何在 MongoDB 中实现这一点?

标签: javascriptmongodbmongodb-query

解决方案


我认为这会得到理想的结果,但不知道处理大量数据的效率如何。

db.A.aggregate([
    {
        $project: {
            _id: 0,
            data: 1
        }
    },
    {
        $lookup:
        {
            from: 'B',
            let: { word: '$data' },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $regexMatch: {
                                input: '$description',
                                regex: '$$word'
                            }
                        }
                    }
                },
                {
                    $project: { _id: 1 }
                }
            ],
            as: 'found'
        }
    },
    {
        $group: {
            _id: null,
            ids: {
                $addToSet: {
                    $arrayElemAt: ['$found', 0]
                }
            }
        }
    },
    {
        $set: {
            ids: {
                $map: {
                    input: '$ids',
                    in: '$$this._id'
                }
            }
        }
    },
    {
        $lookup: {
            from: 'B',
            let: { found_ids: '$ids' },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $not: {
                                $in: ['$_id', '$$found_ids']
                            }
                        }
                    }
                }
            ],
            as: 'docs'
        }
    },
    {
        $unwind: '$docs'
    },
    {
        $replaceWith: '$docs'
    }
])

https://mongoplayground.net/p/YMrYeiUOQdo


推荐阅读