如何在与MongoDB中的其他数组值匹配的数组中查找值

时间:2019-04-18 15:37:05

标签: arrays mongodb mongodb-query

我在MongoDB中有2个集合: 用户:favourite_tags:数组[]和事件:标题:字符串,标签:数组[],所以我的问题是:我如何找到具有至少一个用户的收藏夹标签之一的事件标题?

例如,用户“ A”在他的收藏夹中具有摇滚,舞蹈和食物标签,带有标签的事件是:马拉松(跑步,运动),饮食比赛(食物,饮料)和一般的摇滚乐队音乐会(音乐,摇滚) )。

查找后的预期结果是: 音乐会,饮食比赛

1 个答案:

答案 0 :(得分:0)

我相信可以使用$lookup来做到这一点(一定要参考与您的mongoDB版本匹配的文档)。

在这个答案中,我使用了mongoDB v3.4.19

样本数据

db.getCollection('users').insert(
    {
        name: "bob",
        favourite_tags: ["rock", "dance", "food"]
    }
)
db.getCollection('events').insertMany([
    {
        title: "marathon",
        tags: ["run", "sport"]
    },
    {
        title: "eating contest",
        tags: ["food", "drink"]
    },
    {
        title: "general rock band concert",
        tags: ["music", "rock"]
    }
])

查询至少具有1个匹配用户的事件(结果中包括匹配的用户)

db.getCollection('events').aggregate([
    {
        $lookup: {
            from: "users",
            localField: "tags",
            foreignField: "favourite_tags",
            as: "users"
        }
    },
    {
        $match: {
            users: {
                $ne: []
            }
        }
    }
])

结果

    {
        "title" : "eating contest",
        "tags" : [ 
            "food", 
            "drink"
        ],
        "users" : [ 
            {
                "name" : "bob",
                "favourite_tags" : [ 
                    "rock", 
                    "dance", 
                    "food"
                ]
            }
        ]
    },
    {
        "title" : "general rock band concert",
        "tags" : [ 
            "music", 
            "rock"
        ],
        "users" : [ 
            {
                "name" : "bob",
                "favourite_tags" : [ 
                    "rock", 
                    "dance", 
                    "food"
                ]
            }
        ]
    }

查询将其与事件匹配的用户(包括与之匹配的事件)

db.getCollection('users').aggregate([
    {
        $lookup: {
            from: "events",
            localField: "favourite_tags",
            foreignField: "tags",
            as: "matchingEvents"
        }
    }
])

结果

{
    "name" : "bob",
    "favourite_tags" : [ 
        "rock", 
        "dance", 
        "food"
    ],
    "matchingEvents" : [ 
        {
            "title" : "eating contest",
            "tags" : [ 
                "food", 
                "drink"
            ]
        }, 
        {
            "title" : "general rock band concert",
            "tags" : [ 
                "music", 
                "rock"
            ]
        }
    ]
}