描述:
如果陣列中的所有物件都符合條件,我只想回傳。現在,如果物件陣列中至少有一個條件匹配,它將回傳該物件。
如果你們對這個問題有任何疑問。我會回答請問!
輸入:
[
{
"_id":"4",
"intends":[
{
"_id":"1",
"status":"Packed"
},
{
"_id":"2",
"status":"Packed"
}
]
},
{
"_id":"5",
"intends":[
{
"_id":"3",
"status":"Packed"
},
{
"_id":"4",
"status":"Created"
}
]
}
]
電流輸出:
[
{
"_id":"4",
"intends":[
{
"_id":"1",
"status":"Packed"
},
{
"_id":"2",
"status":"Packed"
}
]
},
{
"_id":"5",
"intends":[
{
"_id":"3",
"status":"Packed"
},
{
"_id":"4",
"status":"Created"
}
]
}
]
預期輸出:
[
{
"_id":"4",
"intends":[
{
"_id":"1",
"status":"Packed"
},
{
"_id":"2",
"status":"Packed"
}
]
}
]
我努力了:
db.collection.find({intends.status: "Packed"})
db.collection.find({intends: {$elemMatch: {status: "Packed"}}})
uj5u.com熱心網友回復:
使用 和 的可能$elemMatch解決$nin方案$not。
,部分將給出至少有一個狀態不是“打包”的元素的所有元素$elemMatch。$nin所以$not將反轉它并給出每個狀態都是“打包”的元素
db.collection.find({
intends: {
"$not": {
"$elemMatch": {
status: {
"$nin": [
"Packed"
]
}
}
}
}
})
演示
更新
因為這里只是檢查 1 值使用$ne而不是$nin
db.collection.find({
intends: {
$not: {
$elemMatch: {
status: {
$ne: "Packed"
}
}
}
}
})
演示
uj5u.com熱心網友回復:
使用aggregation $ redact和$allElementsTrue
在mongoPlayground進行測驗
db.collection.aggregate([
{
"$redact": {
"$cond": [
{
"$allElementsTrue": {
"$map": {
"input": "$intends",
"as": "intend",
"in": {
"$eq": [
"$$intend.status",
"Packed"
]
}
}
}
},
"$$KEEP",
"$$PRUNE"
]
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/440281.html
