MongoDB使用$或

时间:2018-02-14 14:36:37

标签: java mongodb mongodb-query

我正在寻找一个Mongo查询来查找以下文档中的数据。

{
    "key1": [{
        "subkey1": ["america.south.gas"],
        "subkey2": ["9898989898"]
    }],

    "key2": [{
            "subkey1": ["america"],
            "subkey2": ["hsadjsahjsahdjsah879878u9"]
        },
        {
            "subkey1": ["america.south.gas","america"],
            "subkey2": ["hsadjsahjsahdjsah879878u9"]
        },
        {
            "subkey1": ["america.south.#"],
            "subkey2": ["sjadkjsahdkjsahdj989s89d8sa98d9sa"]
        }]
}

我只想要上面提到的文件subkey2作为以下输出:

"subkey2": ["hsadjsahjsahdjsah879878u9"] 
"subkey2": ["sjadkjsahdkjsahdj989s89d8sa98d9sa"]

现在我想用以下查询获取数据: -

db.collectionName.find({$or:[ 
        {"key2.subkey1": "america.south.gas"},   
        {"key1.subkey1": "america.south.#"} 
    ]},
    {"_id": 0, "key2.subkey2.$": 1}
);

但是它向我显示了这个错误:

{ 
    "waitedMS" : NumberLong(0), 
    "ok" : 0, 
    "errmsg" : "Executor error during find command: BadValue: positional operator (key1.$) requires corresponding field in query specifier", 
    "code" : 96 
}

任何想法如何在Mongo查找操作中获取具有多个查询字段的特定字段?

2 个答案:

答案 0 :(得分:1)

此错误......

  

错误:错误:{“waitedMS”:NumberLong(0),“ok”:0,“errmsg”:“查找命令期间执行程序错误:BadValue:位置运算符(key1。$)需要查询说明符中的相应字段” ,“代码”:96}

..是由这个预测引起的:

"key2.subkey2.$": 1

如此,位置运算符:$

根据上述评论,你......

  

只需要上面提到的文件的subkey2如下输出: - “subkey2”:[“hsadjsahjsahdjsah879878u9”]“subkey2”:[“sjadkjsahdkjsahdj989s89d8sa98d9sa”]

以下命令......

db.collection.aggregate([
    {$unwind:'$key2'}, 
    // find the documents having key2.subkey1 = 'america.south.#' or key2.subkey1 = 'america.south.gas'
    {$match:{'key2.subkey1':{$in:['america.south.#','america.south.gas']}}},
    // limit the output to only those key2.subkey2 entries for which the associated key2.subkey1 match the previous $match clause
    {$group:{_id:0,'subkey2':{$push:'$key2.subkey2'}}},
    // only return subkey2
    {$project: {_id: 0, 'subkey2':1}}
])

...将返回:

{
    "subkey2" : [ 
        [ 
            "hsadjsahjsahdjsah879878u9"
        ], 
        [ 
            "sjadkjsahdkjsahdj989s89d8sa98d9sa"
        ]
    ]
}

答案 1 :(得分:0)

@glytching,如果我需要输出如下所示,那么需要在查询中进行更改,也没有重复的输出值。

{     “subkey2”:[“hsadjsahjsahdjsah879878u9”,“sjadkjsahdkjsahdj989s89d8sa98d9sa”]

}