Strontium_99
Strontium_99

Reputation: 1813

Filtering MongoDB collections within collection using MongoDB Shell

Apologies for the nood question. I'm just starting out using MongoDB and MongoDB Shell.

I've got a DB called Dealers that looks a little like this (very simplified):

        [
    {
        "Id": 1,
        "Vehicles": [
        {
            "Manufacturer": "Ford"
        },
        {
            "Manufacturer": "MG"
        },
        {
            "Manufacturer": "Citroen"
        }
        ]
    },
    {
        "Id": 2,
        "Vehicles": [
        {
            "Manufacturer": "Ford"
        },
        {
            "Manufacturer": "Nissan"
        },
        {
            "Manufacturer": "Ford"
        }
        ]
    }
    ]

I'm trying to get my head round how you filter collections within collections EG. Say I wanted to select all the Ford's from Id 2.

I get as far as:

const dealer = database.collection('Dealers');
const result = await dealer.find({Id: 2})

and I tried:

const result = await dealers.find({
    Id: 2,
    Vehicles: [
        {
            Manufacturer: "Ford"
        }
    ]
})

But I know that won't work because it's not iterating through the Vehicles collection. Is this the sort of instance that you would use an aggregation? Like I say, I'm very new to this sort of environment, and would really appreciate any pointers please.

Upvotes: 0

Views: 535

Answers (1)

Shamoon97
Shamoon97

Reputation: 329

I Just have tried. You can use Aggregate function To actually match the items inside the array in the collection. Like the way following query will select all the documents that have id equal to 1 and Manufacturer equal to Ford

db.MyCollection.aggregate([{$match:{Id:1}},{$unwind:"$Vehicles"}, {$match: {"Vehicles.Manufacturer":"Ford"}}]);

It is returning like this. I have used my own Id i.e equal to one you can change this.

enter image description here

Upvotes: 1

Related Questions