我正在尝试查询集合中的数组,如果对象存在于数组中,则将其投影为“ true”。如果对象在数组中不存在,则项目“ false”。我在MongoDB中工作,对此不太熟悉。
在我的场景中,我有两个正在使用的集合。我正在聚集“职员”成员的集合,并且正在对“企业”的集合执行$ lookup函数。在“企业”中,我拥有一系列的企业能力。
例如,我有员工集合
staff = [
...
{_id: 1, businessId: 11},
{_id: 2, businessId: 22},
....
]
业务集合
businesses = [
...
{_id: 11, capabilities: ["claiming", "pushing"]},
{_id: 22, capabilities: ["claiming", "popping"]},
....
]
并具有$ lookup设置,例如
db.getCollection('staff').aggregate([
{
$lookup:
{
from: "businesses",
localField: "businessId",
foreignField: "_id",
as: "business_Info"
}
},
如果在“功能”中出现“声明”,我如何将每个员工的项目投影到$ canClaim:true的值?
答案 0 :(得分:2)
您可以使用$in
聚合运算符检查数组是否包含该值。
db.getCollection("staff").aggregate([
{ "$lookup": {
"from": "businesses",
"localField": "businessId",
"foreignField": "_id",
"as": "business_Info"
}},
{ "$unwind": "$business_Info" },
{ "$addFields": {
"canClaim": { "$in": ["claiming", "$business_Info.capabilities"] }
}}
])
答案 1 :(得分:0)
db.getCollection("staff").aggregate(
// Pipeline
[
// Stage 1
{
$lookup: // Equality Match
{
from: "businesses",
localField: "businessId",
foreignField: "_id",
as: "businessInfo"
}
// Uncorrelated Subqueries
// (supported as of MongoDB 3.6)
// {
// from: "<collection to join>",
// let: { <var_1>: <expression>, …, <var_n>: <expression> },
// pipeline: [ <pipeline to execute on the collection to join> ],
// as: "<output array field>"
// }
},
// Stage 2
{
$project: {
businessId: 1,
businessInfo: {
$arrayElemAt: ['$businessInfo', 0]
}
}
},
// Stage 3
{
$addFields: {
"businessInfo.canClaim": {
$cond: {
if: {
$gte: [{
$indexOfArray: ["$businessInfo.capabilities", 'claiming']
}, 0]
},
then: true,
else: false
}
}
}
},
]
);