MongoDB find query with multiple query field using $or

Prashant Bhagat Source

I am looking for a Mongo query for finding data in the following document.

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

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

I want only subkey2 only of above mentioned document as following output:

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

Now I want to fetch data with following query:-

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

But it is showing me this error:

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

Any idea how can I achieve this for getting specific field with multiple query field in Mongo find operation??

javamongodbmongodb-query

Answers

answered 6 months ago glytching #1

This error ...

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

.. is caused by this projection:

"key2.subkey2.$": 1

Soecifically, the positional operator: $.

According to the comments above, you ...

want only subkey2 only of above mentioned document as following output:- "subkey2": ["hsadjsahjsahdjsah879878u9"] "subkey2": ["sjadkjsahdkjsahdj989s89d8sa98d9sa"]

The following command ...

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}}
])

... will return:

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

answered 6 months ago Anil Singh #2

@glytching, If i need output like that as below given then what need to change in query and also no duplicate output value.

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

}

comments powered by Disqus