【发布时间】:2019-02-21 06:35:31
【问题描述】:
我正在使用 mongo 通过 go 将数据存储在数据库中。所以有两个集合,分别命名为 section 和 fields。 section 集合包含如下文档:
{ "_id" : 2, "name" : "Message", "status" : 1 }
字段集合包含如下文档:-
{
"_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)
如果有任何建议,我将如何更正该查询。
【问题讨论】: