Mongo - 选择没有特定键值对的文档

时间:2016-02-06 02:57:46

标签: mongodb mongodb-query

这是该集合中的示例文档 该集合由多个文档组成,如下面的文档,其中包含“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的原因。 我尝试了什么 -

  1. "currentState.genericParams.key": { $exists: true, $ne: "manual_refund_processed" }
  2. "currentState.genericParams.key": { $exists: true, $nin: [ "manual_refund_processed" ] }

2 个答案:

答案 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")
            }
        ]
    }
}