mongoDB中的子查询问题

时间:2019-02-25 17:44:43

标签: sql mongodb lookup correlated-subquery

我想对MongoDB做一个简单的子查询,但是,在阅读了大量文档之后,仍然没有得到它:( 我使用的代码类似但没有成功:https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

select count(*) from Table1 where Field1 in (SELECT Field2 FROM Table2 where Field3 in ('QWERTY','ASDDF'));

您能帮忙吗? 谢谢。

已编辑: 我已经尝试过类似下面的操作,但是仍然缺少...中的field3过滤器。

db.getCollection("Table1").aggregate(
    [
        { 
            "$group" : {
                "_id" : {

                }, 
                "COUNT(*)" : {
                    "$sum" : NumberInt(1)
                }
            }
        }, 
        { 
            "$project" : {
                "COUNT(*)" : "$COUNT(*)", 
                "_id" : NumberInt(0)
            }
        },
        {
        "$lookup": {
            "from": "Table2",
            "localField": "Field1",
            "foreignField": "Field2" ,
            "as": "data"
            }
        },
{"$match": { "data.Field3": { "$in" : [ "QWERTY", "ASDDF" ]  } }}  
    ], 
    { 
        "allowDiskUse" : true
    }
);

1 个答案:

答案 0 :(得分:0)

如果我正确理解,您会有两个这样的收藏

collection1

[
{
    "c" : 3,
    "field" : 3
},
{
    "b" : 2,
    "field" : 2
},
{
    "a" : 1,
    "field" : 1
}
]

collection2

[
{
    "field1" : 4,
    "field2" : "kghjfdsa"
},
{
    "field1" : 3,
    "field2" : "dsfdgfdghdf"
},
{
    "field1" : 2,
    "field2" : "fdsfsd"
},
{
    "field1" : 1,
    "field2" : "adasd"
}
]

要查询数据,您只需要运行此查询

db.collection2.aggregate([
    {
        $match: {
            field2: {
                $in: ["kghjfdsa", "fdsfsd", "adasd"]
            }
        }
    },
    {
        $lookup: {
            from: "collection1",
            localField: "field1",
            foreignField: "field",
            as: "data"
        }
    },
    {
        $match: {
           "data.field": 1
        } 
    }
])

如果我可以提供其他帮助,请告诉我:)