Querying subdocuments in MongoDB

#1

Hey guys,
I’m just wondering how we can query subdocuments within MongoDB? Currently, I’m trying to execute the following query:

MyCollection.find({infoId:'tLDmtdeYuG9DiGGrL',optimizeParams:{deviceType:'mobile',daytime:'night'}})

This query returns null, but when I change it to the following:

MyCollection.find({infoId:'tLDmtdeYuG9DiGGrL',optimizeParams:{daytime:'night',deviceType:'mobile'}})

I get the matching object. It seems that the key order of the subdocuments is important. Now I’m wondering what would be the right way to execute that query, ignoring the order of the object keys. I know that one solution would be using dot notation, but in this case I would also get documents that have more keys (because they also include both values above)

1 Like
#2

I’ve come across this and I don’t think there is an elegant way, particularly as the number of fields in the subdocument grows. See Stackoverflow for some suggestions.

Since you’re only looking for two fields then I would use:

    infoId: 'tLDmtdeYuG9DiGGrL',
    optimiseParams: { $or: [
        {deviceType: 'mobile', daytime: 'night'},
        {daytime: 'night', deviceType: 'mobile'}
    ]}

Or, if there aren’t many other potential fields in the subdocument and you know them all in advance (no risk of new fields being added in the future) then maybe:

    infoId: 'tLDmtdeYuG9DiGGrL',
    "optimiseParams.deviceType": 'mobile',
    "optimiseParams.daytime": 'night',
    "optimiseParams.otherField": {$exists: false},
    "optimiseParams.anotherField": {$exists: false},
2 Likes
#3

I believe the reason your query depends on field order is b/c you are asking for a document that has a field that matches a specific OBJECT with 2 fields.

I think I like both of @wildhart’s suggestions