使用多个字段的mongodb查找不起作用
我正在尝试使用regCodes集合的siteId从titleInfo集合中获取一些其他信息 我有两套 regcode使用多个字段的mongodb查找不起作用,mongodb,Mongodb,我正在尝试使用regCodes集合的siteId从titleInfo集合中获取一些其他信息 我有两套 regcode { "siteId" : "123A", "registration_code" : "ABC", "used_flag" : true, "Allowed_Use" : 1, "Remaining_Use" : 0, "BatchId" : "SNGL", "CodeDuration" : 180 } 标题信息 {
{
"siteId" : "123A",
"registration_code" : "ABC",
"used_flag" : true,
"Allowed_Use" : 1,
"Remaining_Use" : 0,
"BatchId" : "SNGL",
"CodeDuration" : 180
}
标题信息
{
"title" : "Principles of Microeconomics",
"product_form_detail" : "EPUB",
"final_binding_description" : "Ebook",
"vitalsource_enabled" : false,
"reading_line" : "with InQuizitive and Smartwork5",
"volume" : "",
"protected_content" : {
"ebookSiteIds" : [
"123A"
],
"studySpaceSiteIds" : [],
"iqSiteIds" : []
}
}
下面的查询不工作,正在将“regcodeData”获取为空数组
使用mongodb版本3.6.18
db.getCollection('regcode').aggregate([
{
$match:{
注册代码:“ABC”
}
},
{
$lookup:{
来自:“titleInfo”,
让我们:{
regcode_siteId:“$siteId”
},
管道:[
{
$match:{
$expr:{
$or:[
{
$eq:[
“$protected_content.ebookSiteIds”,
“$$regcode\u站点ID”
]
},
{
$eq:[
“$protected_content.studySpaceSiteIds”,
“$$regcode\u站点ID”
]
},
{
$eq:[
“$protected_content.iqSiteIds”,
“$$regcode\u站点ID”
]
}
]
}
}
}
],
as:“regcodeData”
}
}
])
下面的查询正在按预期工作
db.getCollection('titleInfo').find({
$or:[
{
“受保护的内容.电子书站点ID”:“123A”
},
{
“受保护的内容。StudySpaceSiteId”:“123A”
},
{
“受保护的内容。IQSiteId”:“123A”
}
]
})
您只需使用$unwind
操作符,将preserveNullAndEmptyArrays
选项设置为true
即可展开数组
更新的查询:
db.regCodes.aggregate([
{
$match:{
注册代码:“ABC”
}
},
{
$lookup:{
来自:“titleInfo”,
让我们:{
regcode_siteId:“$siteId”
},
管道:[
{
$REWIND:{
路径:“$protected_content.ebookSiteIds”,
preserveNullAndEmptyArrays:true
}
},
{
$REWIND:{
路径:“$protected_content.studySpaceSiteIds”,
preserveNullAndEmptyArrays:true
}
},
{
$REWIND:{
路径:“$protected_content.iqSiteIds”,
preserveNullAndEmptyArrays:true
}
},
{
$match:{
$expr:{
$or:[
{
$eq:[
“$protected_content.ebookSiteIds”,
“$$regcode\u站点ID”
]
},
{
$eq:[
“$protected_content.studySpaceSiteIds”,
“$$regcode\u站点ID”
]
},
{
$eq:[
“$protected_content.iqSiteIds”,
“$$regcode\u站点ID”
]
}
]
}
}
}
],
as:“regcodeData”
}
}
])
我的错误是试图将数组与字符串匹配
答案如下
db.getCollection('regCodes').aggregate([
{
$match: {
registration_code: 'ABC'
}
},
{
$lookup: {
from: "titleInfo",
let: {
regcode_siteId: "$siteId"
},
pipeline: [
{
$match: {
$expr: {
$or: [
{
$in: [
"$$regcode_siteId",
"$protected_content.ebookSiteIds"
]
},
{
$in: [
"$$regcode_siteId",
"$protected_content.studySpaceSiteIds"
]
},
{
$in: [
"$$regcode_siteId",
"$protected_content.iqSiteIds"
]
}
]
}
}
}
],
as: "regcodeData"
}
}
])