Mindaugas Jukna
Mindaugas Jukna

Reputation: 43

MongoDB querying inside an array of objects

I'm very new to MongoDB, and only have experience in MySQL with databases.

I have this document inside MongoDB:

{
"type": "table",
"name": "pd_locations",
"database": "boatie_db",
"data": [{
    "location_id": "1",
    "name": "Ved slusen (Sluseholmen)",
    "latitude": "12.55013600",
    "longitude": "55.64845000",
    "time_from_slus": "0"
}, {
    "location_id": "2",
    "name": "Fisketorvet",
    "latitude": "12.56373800",
    "longitude": "55.66334900",
    "time_from_slus": "30"
}, {
    "location_id": "3",
    "name": "Kayak Bar",
    "latitude": "12.58679700",
    "longitude": "55.67547700",
    "time_from_slus": "35"
}, {
    "location_id": "4",
    "name": "Reffen",
    "latitude": "12.60740800",
    "longitude": "55.69375000",
    "time_from_slus": "60"
}, {
    "location_id": "5",
    "name": "Nordhavn bassin v. sandkaj",
    "latitude": "12.59589800",
    "longitude": "55.70640400",
    "time_from_slus": "75"
}]}

I'm trying, if possible, querying so i only get one specific object by location id, which is already inside the object.

For example, if i ask for location_id: 1, i want it to return:

{"location_id": "1",
"name": "Ved slusen (Sluseholmen)",
"latitude": "12.55013600",
"longitude": "55.64845000",
"time_from_slus": "0"}

and/or without the ID

{"name": "Ved slusen (Sluseholmen)",
"latitude": "12.55013600",
"longitude": "55.64845000",
"time_from_slus": "0"}

Upvotes: 1

Views: 41

Answers (2)

Rubin Porwal
Rubin Porwal

Reputation: 3845

db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $project: {
                data: {
                    $filter: {
                        input: "$data",
                        as: "data",
                        cond: {
                            $eq: ["$$data.location_id", "1"]
                        }
                    }
                }
            }
        },

    ]



);

Upvotes: 0

Tom Slabbaert
Tom Slabbaert

Reputation: 22276

Yes it is possible, use $elemMatch:

db.collection.find(
    {
        // query to match your on object
    },
    {
        data: {
            $elemMatch: {
                location_id: "1"
            }
        }
    }
);

EDIT:

For further structure manipulation you'll have to use an aggregation pipeline as far as i know.

db.collection.aggregate([
    {
        $match: {
            // your match query
        }
    },
    {
        $project: {
            data: {
                $map: {
                    input: {$filter: {input: "$data", as: "d", cond: {$eq: ["$$d.location_id", "1"]}}},
                    as: "d",
                    in: "$$d.name"
                }
            }
        }
    }
]);

Upvotes: 1

Related Questions