mongodb-如何查询sql的“intersect”?

xxe27gdn  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(278)

我有一个关于mongodb查询中的intersect查询的问题。
我想在mongodb中进行如下sql查询。

(select course_id from section where semester = 'fall' and year = '2009') 
intersect 
(select course_id from section where semester = 'spring' and year = '2010');

在我的mongodb中,节集合数据结构如下。

{ 
"_id" : {
    "course_id" : "486", 
    "sec_id" : "1", 
    "semester" : "Fall", 
    "year" : 2009.0
}, 
"course_id" : "486", 
"sec_id" : "1", 
"semester" : "Fall", 
"year" : 2009.0, 
"building" : "Whitman", 
"room_number" : "134", 
"time_slot_id" : "K"

}
如何查询得到与sql语言相同的结果?

xfb7svmp

xfb7svmp1#

这并不完全性感,但你可以这样做:

db.collection.aggregate([
    {
        $match: {
            $or: [
                {
                    $and: [
                        {
                            year: 2009
                        },
                        {
                            semester: "fall"
                        }
                    ]
                },
                {
                    $and: [
                        {
                            year: 2010
                        },
                        {
                            semester: "spring"
                        }
                    ]
                }
            ]
        }
    },
    {
        $group: {
            _id: "$course_id",
            years_x_semester: {$addToSet: {year: "$year", semester: "$semester"}},
        }
    },
    {
        $match: {
            "years_x_semester.1": {$exists: true}
        }
    }
])

相关问题