为什么我的mongodb查询没有给我预期的结果?

问题描述 投票:0回答:1

我正在使用mongodb将数据存储在数据库中。所以有两个名为section和fields的集合。 section collection包含如下文档:

{ "_id" : 2, "name" : "Message", "status" : 1 }

和fields集合包含如下文件: -

{
    "_id" : 6,
    "lead_section_id" : 2,
    "help_text" : "This is a tool tip",
    "name" : "Test11",
    "status" : 9
}
{
    "_id" : 7,
    "lead_section_id" : 2,
    "help_text" : "This is a tool tip",
    "name" : "Test11",
    "status" : 1
}

当我使用lead_section_id is 2聚合获取记录时,查看包含$lookup的字段集合文档然后它将返回字段集合中的两个文档,而我在传递状态时在查询中等于0,1所以结果为什么会产生结果我喜欢下面

{
    "id": 2,
    "name": "Message",
    "slug": "Name",
    "status": 1,
    "fields": [
        {
            "id": 6,
            "lead_section_id": 2,
            "field_type": "text",
            "help_text": "This is a tool tip",
            "name": "Test11",
            "placeholder": "Enter the name",
            "slug": "test11111111",
            "status": 9
        },
        {
            "id": 7,
            "lead_section_id": 2,
            "field_type": "text",
            "help_text": "This is a tool tip",
            "name": "Test11",
            "placeholder": "Enter the name",
            "slug": "test11asdasd111111",
            "status": 1
        }
    ]
}

在golang查询像

var queryIn []bson.M
queryIn = append(queryIn, bson.M{"_id": 2})
queryIn = append(queryIn, bson.M{"fields.status": bson.M{operator: []int{1,0}}})
// database connection
getCollection := sessionCopy.DB("Database").C("lead_section")
pipe := getCollection.Pipe([]bson.M{
    bson.M{
        "$lookup": bson.M{
            "localField":   "_id",
            "from":         "lead_field",
            "foreignField": "lead_section_id",
            "as":           "fields"}},
    bson.M{"$match": bson.M{"$and": queryIn}},
})

err = pipe.One(&data)
fmt.Println(data, err)

请问如何纠正该查询的任何建议。

mongodb mgo
1个回答
0
投票

那么使用该查找,您可以在文档中获得两个子文档,并且至少有一个与您的状态匹配,因此匹配。因此,如果要排除具有错误状态的子文档/字段,则需要将其展开并再次分组,或者投影和过滤字段数组。

© www.soinside.com 2019 - 2024. All rights reserved.