为什么mongodb查询未返回结果

时间:2019-02-20 12:45:45

标签: mongodb mgo

我正在使用$lookup$match聚合,以根据特定条件从两个集合中获取结果。以下是我在golang代码中使用的查询:-

 getCollection := sessionCopy.DB("Database").C("lead_section")
pipe := getCollection.Pipe([]bson.M{
    bson.M{"$match": bson.M{"status": 1}},
    bson.M{
        "$lookup": bson.M{
            "localField":   "_id",
            "from":         "lead_field",
            "foreignField": "lead_section_id",
            "as":           "custom_fields"}},
    // bson.M{"$unwind": "$custom_fields.status"},
    bson.M{"$match": bson.M{"custom_fields.status": 1}}})

以上查询将返回此结果

 [
        {
            "id": 1,
            "name": "Message",
            "status": 1,
            "custom_fields": [
                {
                    "id": 3,
                    "lead_section_id": 1,
                    "field_type": "text",
                    "help_text": "This is a tool tip",
                    "name": "Test11",
                    "status": 0
                },
                {
                    "id": 4,
                    "lead_section_id": 1,
                    "field_type": "text",
                    "help_text": "This is a tool tip",
                    "name": "Test11",
                    "status": 1
                },
                {
                    "id": 5,
                    "lead_section_id": 1,
                    "field_type": "text",
                    "help_text": "This is a tool tip",
                    "name": "Test11",
                    "status": 1
                }
            ]
        }
    ]

但是我希望管道产生的结果只有status 1。但是在custom_fields的第一条记录中,id:3的记录是status:0

2 个答案:

答案 0 :(得分:1)

要实现此目的,您需要使用$lookup with multiple join conditions

例如(使用mongo shell):

from wand.image import Image

with Image() as img:
    img.options['gradient:vector'] = '10,10,75,75'
    img.pseudo(256, 256, 'gradient:white-black')
    img.save(filename='output.png')

答案 1 :(得分:0)

$match是如何处理数组字段的。它在任何子文档中寻找匹配项。在这种情况下,其他两个子文档(标识4和5)的状态为1,因此整个结构被认为是匹配的,并进一步传递。

换句话说,它过滤顶级文档。它不过滤嵌套数组。

相关问题