mongodb - 为什么我的 mongodb 查询没有给我预期的结果?
问题描述
我正在使用 mongo 将数据存储在数据库中。所以有两个集合,分别命名为 section 和 fields。部分集合包含一个文档,如:
{ "_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)
请问我将如何更正该查询的任何建议。
解决方案
好吧,通过该查找,您可以将两个子文档都放入您的文档中,并且至少有一个与您的状态相匹配,因此它是匹配的。因此,如果您想排除状态错误的子文档/字段,您需要展开它并再次分组,或者您投影并过滤您的字段数组。
推荐阅读
- sql - PostgreSQL age() 函数:在不同月份登陆时出现不同/意外的结果
- heroku - 包含 image-webpack-loader 时 Heroku webpack 部署错误
- xamarin.forms - 无法从程序集中加载“Xamarin.Forms.Build.Tasks.GetTasksAbi”任务
- appveyor - 在特定提交上触发 Appveyor 构建
- python - 如何设置 Kivy GridLayout 宽度
- python - 在 str.join 为什么列表必须始终包含字符串?
- python-3.x - 预测语句中的 XGboost 功能不匹配错误
- java - 使用带有 Java DSL 配置的 Spring 集成连接到 Weblogic JMS 队列
- sql - 如何替换字符串中的值,除了最后一次出现在oracle中的特定值
- c++ - 如何更改 Excel DSN 的默认工作簿?