javascript - Mongoose 从对象数组中获取与对象项匹配的对象

标签 javascript mongodb mongoose

我想找到与 courseID 匹配的单个文档,但在文档内仅包含 ma​​terials 数组中的 moduleNo 与该文档匹配的对象我给。但我当前使用的查询似乎返回了正确的文档,但也返回了 ma​​terials 数组中的所有对象。任何帮助将不胜感激。

我的架构,

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
  }
]

https://mongoplayground.net/p/vdPVbce6WkX

关于javascript - Mongoose 从对象数组中获取与对象项匹配的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72758546/

相关文章:

javascript - 在 if 语句中,undefined 等于 false

java - 使用 JPATest 和 MongoDB Test 为 Polyglot Springboot 编写测试

mongodb - 如何从 Mongoose 模型对象中获取集合名称

node.js - 使用 mongoose 获取子文档的 Node api

javascript - 如何比较javascript中的两个字符串if条件

javascript - localeCompare 为不同的 unicode 符号返回 0

javascript - 关于客户端散列逻辑的问题

mongodb - 返回所有 int 类型的年龄

javascript - 在文档数组 Mongoose 中获取精确的子文档

mongodb - 如果 Mongoose.connect 不存在,它会默认创建一个 Mongo 数据库吗?