所以我有一个问卷模型:
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
。我还想获取 title
和 category
以及所有其他字段。但我似乎找不到办法做到这一点。
最佳答案
既然你有这种情况'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
注意:我们使用了聚合,因为您想要返回 answers
具有匹配元素的数组或空数组。您也可以使用 $project
而不是$addFields
根据需要转换输出。
关于mongodb - Mongoose 仅从数组中获取特定对象,如果没有则为空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61603590/