mongodb 如何从mongoose模式中查找文档(给定一个具有ID的对象数组)

unhi4e5o  于 2022-12-11  发布在  Go
关注(0)|答案(1)|浏览(226)

I am trying to find some documents given an array of objects and inside each object, there is an id "courseId" which will be used to find the required documents from the schema with the same id. Here is the array of objects:

courseIds =  [
{"courseId":"638c139b147e2173163fd976",
"_id":"63906c07b9b09cd81e48480d"
},
{"courseId":"638c131a147e2173163fd96b",
"_id":"63908c9f1897b57aa6ece69f"
}]

and if the schema contains the following objects:

const courseSchema =
[{
"_id":"638c131a147e2173163fd96b",
"courseTitle":"Neural Networks",
"price":"5000",
"shortSummary":"Its a lovely course about NNs, Sequence Models.",
"subject":"Deep Learning"
},
{
"_id":"638c139b147e2173163fd976",
"courseTitle":"Graphics",
"price":"3000",
"shortSummary":"Its a lovely course about Projection, 2D & 3D Transformations.",
"subject":"Computer Graphics"
},
{
"_id":"638c131a147e9053163fd281",
"courseTitle":"Operating Systems",
"price":"4500",
"shortSummary":"Its a lovely course about Scheduling, learning about drivers and peripherals.",
"subject":"Hardware"
}]

What I want to do is I want to find/return only the courses from the courseSchema whose ids are present in the courseIds array, like here it would only return two courses:

{
"_id":"638c131a147e2173163fd96b",
"courseTitle":"Neural Networks",
"price":"5000",
"shortSummary":"Its a lovely course about NNs, Sequence Models.",
"subject":"Deep Learning"
},
{
"_id":"638c139b147e2173163fd976",
"courseTitle":"Graphics",
"price":"3000",
"shortSummary":"Its a lovely course about Projection, 2D & 3D Transformations.",
"subject":"Computer Graphics"
}

since their ids "_id" are present in the courseIds array ("courseId == _id").
I tried to do the following:

const docs = courseSchema.find().where('_id').in(courseIds);

and

const docs = courseSchema.find({ '_id': { $in: courseIds} });

and it always return an empty array (no matches). Why doesn't it work?

t40tm48m

t40tm48m1#

courseIds id是一个数组对象,为了使_id与数组中的$匹配,必须是only _id,如[“638 c139 b147 e2173163 fd 976”,“638 c131 a147 e2173163 fd 96 b”]。
为此,您可以从courseIds数组对象中创建另一个数组,并将其用作带有$in查询。

courseIds =  [
        {
            "courseId":"638c139b147e2173163fd976",
            "_id":"63906c07b9b09cd81e48480d"
        },
        {
            "courseId":"638c131a147e2173163fd96b",
            "_id":"63908c9f1897b57aa6ece69f"
        }
    ] //Your courseIds array object

    let onlyIds=[] // declaring array to store only _ids

    for(let i=0;i<courseIds.length;i++){
        if(!onlyIds.includes(courseIds[i].courseId)) //checking id exist in array, if not exist push _id to onlyIds aarray
            onlyIds.push(courseIds[i].courseId); //push _id
    }

    console.log(courseId)//output=>["638c139b147e2173163fd976","638c131a147e2173163fd96b"]
    const docs = courseSchema.find({ _id: { $in: onlyIds } }); //final query

相关问题