我想找到与 courseID 匹配的单个文档,但在文档内仅包含 materials 数组中的 moduleNo 与该文档匹配的对象我给。但我当前使用的查询似乎返回了正确的文档,但也返回了 materials 数组中的所有对象。任何帮助将不胜感激。
我的架构,
const materialSchema = new mongoose.Schema({
courseID: String,
materials: [
{
moduleNo: Number,
moduleMaterial: String,
},
],
});
我的代码/查询,
exports.getMaterials = (req, res) => {
const { courseID, moduleNo } = req.query;
Material.findOne(
{ courseID, "materials.moduleNo": moduleNo },
(err, result) => {
if (err) {
console.error(err);
} else {
res.json(result);
}
}
);
};
最佳答案
方式 1:使用 $elemMatch项目领域运营商
The $elemMatch operator limits the contents of an array field from the query results to contain only the first element matching the $elemMatch condition
Result : Returns only one matching array element
语法:
db.collection.find(query,projection)
db.collection.find({
"field": field_value
},{
"array_name":{
$elemMatch:{"key_name": value }
},
field:1,
field_2:1,
field_3:0
})
https://mongoplayground.net/p/HKT1Gop32Pq
方式 2:数组字段限制 array.$在项目领域 *
Result : Returns only one matching array element
db.collection.find({
"field": field_value,
"array_name.key_name": value
},{
"array_name.$":1,
field:1,
field_2:1,
field_3:0
});
https://mongoplayground.net/p/Db0azCakQg9
更新:使用 MongoDB 聚合
Result : Returns multiple matching array elements
db.collection.aggregate([
{
"$unwind": "$materials"
},
{
"$match": {
"courseID": "Demo",
"materials.moduleNo": 1
}
}
])
将返回输出:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"courseID": "Demo",
"materials": {
"moduleMaterial": "A",
"moduleNo": 1
}
},
{
"_id": ObjectId("5a934e000102030405000000"),
"courseID": "Demo",
"materials": {
"moduleMaterial": "B",
"moduleNo": 1
}
}
]
如果你想格式化输出:
db.collection.aggregate([
{
"$unwind": "$materials"
},
{
"$match": {
"courseID": "Demo",
"materials.moduleNo": 1
}
},
{
"$group": {
"_id": {
"courseID": "$courseID",
"moduleNo": "$materials.moduleNo"
},
"materials": {
"$push": "$materials.moduleMaterial"
}
}
},
{
"$project": {
"_id": 0,
"courseID": "$_id.courseID",
"moduleNo": "$_id.moduleNo",
"materials": "$materials"
}
}
])
将返回结果为:
[
{
"courseID": "Demo",
"materials": [
"A",
"B"
],
"moduleNo": 1
}
]
关于javascript - Mongoose 从对象数组中获取与对象项匹配的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72758546/