在我的应用程序中,我有一个民意测验集合,a文档如下所示;
/* POLLS */
{
...
"type": "COMMON",
"__v": {
"$numberInt": "0"
},
"targets": [
{
"code": "city",
"logic": "eq",
"value": "4"
},
{
"code": "city",
"logic": "eq",
"value": "15"
}
]
}
目标键是一个包含目标对象的数组
每个目标的代码可以是城市或性别
因此,这意味着"性别">可能在民意调查文档中找不到。
根据这一点,在获取轮询时,如果代码存在,我希望这些轮询与我的用户字段匹配。
例如从用户订阅源获取民意调查时,
如果民意调查包含性别目标,我希望查找与我的用户性别匹配的民意调查。
我的代码是这样的:
Poll.find({
state: "PUBLISHED",
approval: "APPROVED",
$or: [
{
targets: {
$exists: true,
$eq: []
}
},
{
targets: {
$exists: true,
$ne: [],
$all: [
{
$elemMatch: {
code: {
$exists: true,
$eq: "city"
},
value: {
$eq: foundUser.cityCode // equals to 4 in this example
}
}
},
{
$elemMatch: {
code: {
$exists: true,
$eq: "gender"
},
value: {
$eq: foundUser.gender // equals to m in this example
}
}
}
]
}
}
]
})
但是,
我在上面写的民意调查文档的列表返回为空。
当下面的部分注释掉时,代码将返回正确的轮询。
Poll.find({
state: "PUBLISHED",
approval: "APPROVED",
$or: [
{
targets: {
$exists: true,
$eq: []
}
},
{
targets: {
$exists: true,
$ne: [],
$all: [
{
$elemMatch: {
code: {
$exists: true,
$eq: "city"
},
value: {
$eq: foundUser.cityCode // equals to 4 in this example
}
}
},
// {
// $elemMatch: {
// code: {
// $exists: true,
// $eq: "gender"
// },
// value: {
// $eq: foundUser.gender // equals to m in this example
// }
// }
// }
]
}
}
]
})
在针对性别或国家的情况下,有人能帮助我返回正确的民意调查吗
谢谢,奥努尔
Return targets字段是一个数组,其元素与数组中的$elemMatch标准匹配
尝试该查询
Poll.find({
state: "PUBLISHED",
approval: "APPROVED",
$or: [
{
targets: {
$exists: true,
$eq: []
}
},
{
targets: {
$exists: true,
$ne: [],
$all: [
{
$elemMatch: {
code: {
$exists: true,
$eq: "city"
},
value: {
$eq: "4" // equals to 4 in this example
}
}
}
]
}
},
{
targets: {
$exists: true,
$ne: [],
$all: [
{
$elemMatch: {
code: {
$exists: true,
$eq: "gender"
},
value: {
$eq: 'm' // equals to m in this example
}
}
}
]
}
}
]
})