这是该集合中的示例文档 该集合由多个文档组成,如下面的文档,其中包含“genericParams”中的可变数组元素.-
"currentState" : {
"genericParams" : [
{
"key" : "sms_email_count",
"value" : 3
},
{
"key" : "first_sms_email_time",
"value" : NumberLong("1450691202568")
},
{
"key" : "second_sms_email_time",
"value" : NumberLong("1450691202568")
},
{
"key" : "third_sms_email_time",
"value" : NumberLong("1450691202568")
},
{
"key" : "manual_refund_processed",
"value" : "false"
}
]
}
我想得到所有这些文件,其中“key”不等于“manual_refund_processed”。
同时我想要“genericParms”数组的所有元素,这就是我没有使用$unwind
的原因。
我尝试了什么 -
"currentState.genericParams.key": { $exists: true, $ne: "manual_refund_processed" }
"currentState.genericParams.key": { $exists: true, $nin: [ "manual_refund_processed" ] }
答案 0 :(得分:1)
尝试过滤器:https://docs.mongodb.org/manual/reference/operator/aggregation/filter/
$filter: {
input: "$genericParams",
as: "genericParam",
cond: { $ne: [ "$$genericParam.key", "manual_refund_processed" ] }
}
答案 1 :(得分:1)
此代码段会为您提供准确的结果。假设您的数据存储在名为 state 的集合中
db.state.aggregate([
{$unwind:"$currentState.genericParams"},
{$match:{"currentState.genericParams.key":{$ne:"manual_refund_processed"}}},
{$group:{_id:"$_id", genericParams:{$push:"$currentState.genericParams"}}},
{$project:{_id:0, currentState: { genericParams:"$genericParams"}}}
]).pretty()
或
db.state.aggregate([
{$project:
{_id:0, currentState:{genericParams:
{ $filter:
{ input: "$currentState.genericParams", as: "genericParam", cond:
{ $ne: [ "$$genericParam.key", "manual_refund_processed" ]}}}}}}
]).pretty()
输出是:
{
"currentState" : {
"genericParams" : [
{
"key" : "sms_email_count",
"value" : 3
},
{
"key" : "first_sms_email_time",
"value" : NumberLong("1450691202568")
},
{
"key" : "second_sms_email_time",
"value" : NumberLong("1450691202568")
},
{
"key" : "third_sms_email_time",
"value" : NumberLong("1450691202568")
}
]
}
}