Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying a property that is in a deeply nested array

So I have this document within the course collection

{
 "_id" : ObjectId("53580ff62e868947708073a9"),
    "startDate" : ISODate("2014-04-23T19:08:32.401Z"),
    "scoreId" : ObjectId("531f28fd495c533e5eaeb00b"),
    "rewardId" : null,
    "type" : "certificationCourse",
    "description" : "This is a description",
    "name" : "testingAutoSteps1",
    "authorId" : ObjectId("532a121e518cf5402d5dc276"),
    "steps" : [ 
        {
            "name" : "This is a step",
            "description" : "This is a description",
            "action" : "submitCategory",
            "value" : "532368bc2ab8b9182716f339",
            "statusId" : ObjectId("5357e26be86f746b68482c8a"),
            "_id" : ObjectId("53580ff62e868947708073ac"),
            "required" : true,
            "quantity" : 1,
            "userId" : [ 
                ObjectId("53554b56e3a1e1dc17db903f")
            ]
        },...

And I want to do is create a query that returns all courses that have a specific userId in the userId array that is in the steps array for a specific userId. I've tried using $elemMatch like so

Course.find({ 
    "steps": { 
        "$elemMatch": { 
            "userId": { 
                "$elemMatch": "53554b56e3a1e1dc17db903f"
            }
        }
    }
},

But It seems to be returning a empty document.

like image 632
Austin Davis Avatar asked Oct 20 '22 09:10

Austin Davis


1 Answers

I think this will work for you, you have the syntax off a bit plus you need to use ObjectId():

db.Course.find({ steps : { $elemMatch: { userId:ObjectId("53554b56e3a1e1dc17db903f")} } })
like image 155
John Petrone Avatar answered Oct 23 '22 03:10

John Petrone