Ragy Isaac
Ragy Isaac

Reputation: 1458

Querying MongoDB collections

Given the following three MongoDB collections:

db.array.insertMany([{
    "field_1": [
        {
            "field_11": [{
                "field_22": "Left field_23 Far",
                "field_23": "Right field_23"
            }],
            "field_12": [{
                "field_22": "Left field_23 Far",
                "field_23": "Right field_23"
            }],
            "field_13": [{
                "field_22": "Left field_23 Far",
                "field_23": "Left field_23"
            }],
            "field_14": [{
                "field_23": "Left field_23",
                "field_22": "Left field_23 Far"
            }]
        }
    ]
}])

db.noArray.insertMany([{
    "field_1":
    {
        "field_11": [{
            "field_22": "Left field_23 Far",
            "field_23": "Right field_23"
        }],
        "field_12": [{
            "field_22": "Left field_23 Far",
            "field_23": "Right field_23"
        }],
        "field_13": [{
            "field_22": "Left field_23 Far",
            "field_23": "Left field_23",

        }],
        "field_14": [{
            "field_23": "Left field_23",
            "field_22": "Left field_23 Far"
        }]
    }
}])

db.noArrayArray.insertMany([{
    "field_1":
    {
        "field_11": {
            "field_22": "Left field_23 Far",
            "field_23": "Right field_23"
        },
        "field_12": {
            "field_22": "Left field_23 Far",
            "field_23": "Right field_23"
        },
        "field_13": {
            "field_22": "Left field_23 Far",
            "field_23": "Left field_23"
        },
        "field_14": {
            "field_23": "Left field_23",
            "field_22": "Left field_23 Far"
        }
    }
}])

I would like to query each collection separately and extract "field_11". The result from each of the three collections should be the same. The expected output is:

"field_11": {
            "field_22": "Left field_23 Far",
            "field_23": "Right field_23"}

Thank you in advance for your technical expertise

Upvotes: 0

Views: 58

Answers (1)

s7vr
s7vr

Reputation: 75914

You can try below aggregation queries for each of the collection. Use $arrayElemAt to convert array field at position to document.

db.array.aggregate({$project:{_id:0, field_11:{$arrayElemAt:[{$arrayElemAt:["$field_1.field_11", 0]}, 0]}}});

db.noArray.aggregate({$project:{_id:0, field_11:{$arrayElemAt:["$field_1.field_11", 0]}}});

db.noArrayArray.aggregate({$project:{_id:0, field_11:"$field_1.field_11"}});

You can also use db.collectionname.distinct("field_1.field_11") for all collections to get response like below

[ { "field_22" : "Left field_23 Far", "field_23" : "Right field_23" } ]

Upvotes: 1

Related Questions