简体   繁体   English

如何在mongodb中的文档数组中查找元素?

[英]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. 当我使用schoolid和studentid查找学生信息时,上述架构仅使用schoolid而不是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. 您已将students as an array - students[] -students students as an array - students[] ,仅使用students并传递studentid的值,查询将返回结果。

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);
        });
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MongoDb,NodeJs - 如何通过数组元素的 id 搜索文档来查找文档 - MongoDb, NodeJs - How to find a document by searching it by id of an array element 如果Mongoose数组中包含元素,则查找Mongodb文档 - Find a Mongodb document if it contains an element in the array in mongoose 查找 mongodb 文档的数组中是否存在单个数组元素 - find whether individual array element exists in the mongodb document's array MongoDB:如何在文档数组元素中搜索 - MongoDB: How to search in document array element 如何在 mongodb 中查询文档数组的元素 - How to query element of array of document in mongodb 如何在 mongoDB 文档中查找和打印对象数组 - How to find and print array of objects in mongoDB document 如何在MongoDB / Node JS中的文档中查找和编辑数组元素的属性? - How to find and edit the property of an array element inside a document in MongoDB/Node JS? MongoDB:如何查找与指定列表共享列表元素的文档 - MongoDB: How to find a document sharing a list element with specified list 如何使用Monk在MongoDB中插入带有子文档数组元素的文档 - How to insert a document with a subdocument array element in MongoDB with Monk 如何在 Mongodb 中计算同一文档中两个数组的元素频率 - How to calculate frequency of element for two array in same document with arregation in Mongodb
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM