[英]Find document with specific value from array within an array of subdocuments
[英]Mongo find if any possible field in array of subdocuments has value
我在Collection
上運行aggregate
,並使用對另一個子Collection
的查找。
每個孩子可能有也可能沒有可以包含String
的字段 ( foo
)。
我想project
一個Boolean
,如果這些field
中的至少一個具有任何子子subdocuments
的String
。
所以我可以有類似的東西
db.Parent.aggregate([
{
'$lookup': {
'from': 'Children',
'localField': '_id',
'foreignField': 'parentId',
'as': 'CHILDREN'
}
}, {
childHasFoo: {
"$CHILDREN" : {$elemMatch: {foo: {$ne: ''}}}
}
}
]
你可以看到我對childHasFoo
的投影。 我想我可以使用$elemMatch
或$anyElementTrue
。 請記住, foo
也可能不存在於一個/所有subdocuments
中。 所以需要考慮到這一點。
謝謝!
$map
數組運算符迭代CHILDREN
數組的循環,$ne
檢查您的狀況,這將返回 boolean 值$anyElementTrue
檢查任何元素是否為真 {
$addFields: {
childHasFoo: {
$anyElementTrue: {
$map: {
input: "$CHILDREN",
in: { $ne: ["$$this.foo", ""] }
}
}
}
}
}
第二個選擇更准確的條件,
$trim
從字符串中刪除空格$not
和$in
是字符串空 "" 或null
然后為 false 否則為 true {
$addFields: {
childHasFoo: {
$anyElementTrue: {
$map: {
input: "$CHILDREN",
in: {
$not: {
$in: [
{ $trim: { input: "$$this.foo" } },
["", null]
]
}
}
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.