mongodb - Mongoose 仅​​从数组中获取特定对象,如果没有则为空数组

标签 mongodb mongoose mongodb-query aggregation-framework

所以我有一个问卷模型:

const schema = new mongoose.Schema({
  title: String,
  category: String,
  description: String,
  requirementOption: String,
  creationDate: String,
  questions: [],
  answers: []
})

如您所见,答案是一个数组。该数组包含具有此结构的对象

{
  "participantEmail": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5724383a32123a363e3b17323a363e3b79323a363e3b" rel="noreferrer noopener nofollow">[email protected]</a>"      
  "currentIndex": 14,
  ...
}

现在我想通过 ID 获取特定的调查问卷,但在答案数组中我只想要特定的参与者电子邮件。因此,answers 数组应该只有一个元素,或者没有元素。但如果答案数组中没有此类电子邮件,我不想得到 null 结果。

我弄清楚如何使用此查询从数组中获取特定元素:

dbModel.findOne({_id: id, 'answers': {$elemMatch: {participantEmail: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87f4e8eae2c2eae6eeebc7e2eae6eeeba9e4e8ea" rel="noreferrer noopener nofollow">[email protected]</a>"}}}, {'answers.$': 1}).exec();

如果该电子邮件存在于答案数组中,我将得到:

 "data": {
    "questionnaireForParticipant": {
      "id": "5d9ca298cba039001b916c55",
      "title": null,
      "category": null,
      "creationDate": null,
      "description": null,
      "questions": null,
      "answers": [
        {
          "participantEmail": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1764787a72527a767e7b57727a767e7b3974787a" rel="noreferrer noopener nofollow">[email protected]</a>",
          ....
         }

    }
  }

但是如果该电子邮件不在答案数组中,我将只得到 null。我还想获取 titlecategory 以及所有其他字段。但我似乎找不到办法做到这一点。

最佳答案

既然你有这种情况'answers': {$elemMatch: {participantEmail: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e3d21232b0b232f27220e2b232f2722602d2123" rel="noreferrer noopener nofollow">[email protected]</a>"}}.findOne() 的过滤器部分- 如果给定_id文档 answers. participantEmail 中没有元素数组与输入值 "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c2f33313919313d35301c39313d3530723f3331" rel="noreferrer noopener nofollow">[email protected]</a>" 匹配然后.findOne()将返回null作为输出。因此,如果您想返回文档,而不管 answers 中是否存在匹配元素。数组与否,然后尝试下面的查询:

db.collection.aggregate([
  {
    $match: { "_id": ObjectId("5a934e000102030405000000") }
  },
  /** addFields will re-create an existing field or will create new field if there is no field with same name */
  {
    $addFields: {
      answers: {
        $filter: { // filter will result in either [] or array with matching elements
          input: "$answers",
          cond: { $eq: [ "$$this.participantEmail", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afdcc0c2caeac2cec6c3efcac2cec6c381ccc0c2" rel="noreferrer noopener nofollow">[email protected]</a>" ] }
        }
      }
    }
  }
])

测试: mongoplayground

引用: aggregation-pipeline

注意:我们使用了聚合,因为您想要返回 answers具有匹配元素的数组或空数组。您也可以使用 $project而不是$addFields根据需要转换输出。

关于mongodb - Mongoose 仅​​从数组中获取特定对象,如果没有则为空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61603590/

相关文章:

C# MongoDB UpdateManyAsync with Set 方法抛出异常

macos - MongoDB 无法在 Mac 上启动

javascript - 如何更新子文档并删除子文档中数组的单个对象?

mongodb - 如何在 mongo 聚合 $group $cond 中使用 $in 或 $nin

json - MongoDB、NodeJS : updating an embedded document with new members

mongodb - 如何使用 Spring Data MongoDB 结合文本和地理查询?

javascript - 尝试在 Mongoose 中填充,但它不起作用(nodejs)

node.js - Mongodb插入空日期

javascript - 从查询中的查询访问 MongoDB 值

mongodb - 集成 Grails 和 MongoDB?需要任何教程