简体   繁体   中英

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.

我认为这对你有用,你有一些语法加上你需要使用ObjectId():

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

The $elemMatch usage is not necessary unless you actually have compound sub-documents in that nested array element. And also is not necessary unless the value being referenced could possibly duplicate in another compound document.

Since this is an ObjectId we are talking about, then it's going to be unique, at least within this array. So just use the "dot-notation" form:

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

Go back and look at the $elemMatch documentation. In this case, the direct "dot-notation" form is all you need

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM