Request for a property located in a deeply nested array

So I have this document in 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 create a query that returns all those that have a specific userIdin the array userIdthat is in the array stepsfor the specific userId. I tried using $elemMatchlike this

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

But it looks like it is returning an empty document.

+4
source share
2 answers

Use is not required if you actually do not have compound subdocuments in this nested element of the array, and it is also not required if the reference to the value cannot be duplicated in another compound document. $elemMatch

ObjectId, , , , . "-":

Course.find({
    "steps.userId": ObjectId("53554b56e3a1e1dc17db903f")
},

$elemMatch. "-"

+1

, , , ObjectId():

db.Course.find({ steps : { $elemMatch: { userId:ObjectId("53554b56e3a1e1dc17db903f")} } })
+1

Source: https://habr.com/ru/post/1537933/


All Articles