简体   繁体   中英

How to find an element in an array of a document in mongodb?

I have a code like the following.

router.get('/Child_Profile/:SchoolId/:childId',function(req,res,next){
childModel.find({"schoolid":req.params.SchoolId,"students[]":req.params.ChildId}, function (err, result) {       
        if (err) 
            {
            return console.log(err);
        }
    res.json(result);
        });
  });

Ex Collection

{
"schoolid":"1wer",
"students":["121","232"],
"profilepic":"http://wed"
}

While i am finding the student info using schoolid and studentid the above schema was finding with only schoolid, not with the studentid. Thanks in advance

You have reffered students as an array - students[] , use just students and pass on the value of the studentid, the query will return you results.

Mongo shell query for the collection

{
        "_id" : ObjectId("59e9cfd4f4896dbabfc15f45"),
        "schoolid" : "1wer",
        "students" : [
                "121",
                "232"
        ],
        "profilepic" : "http://wed"
}

db.collection.find({students:"121"});

Modified query

router.get('/Child_Profile/:SchoolId/:childId',function(req,res,next){
childModel.find({"schoolid":req.params.SchoolId,"students":req.params.ChildId}, function (err, result) {       
        if (err) 
            {
            return console.log(err);
        }
    res.json(result);
        });
  });

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