How can I retrieve only the subdocument in a mongodb document?
如何只检索mongodb文档中的子文档?
const result = await context.parents.find(
{
_id: mongoose.Types.ObjectId(args.parentId),
children: {
$elemMatch: {
_id: mongoose.Types.ObjectId(args.childId),
}
}
},
{
_id: 0,
'children.$': 1
});
To access to the subdocument I need to do this:
要访问子文档,我需要这样做:
if (result) {
return result[0].toObject().children[0];
}
Here is the document schema:
这是文档架构:
const ParentSchema = new mongoose.Schema({
firstName: { type: mString, required: true, trim: true },
lastName: { type: mString, required: true, trim: true },
birthdate: mDate,
created: { type: mDate, required: true, default: Date.now },
children: [{
startDate: { type: mDate, required: true }
}],
});
Is there a way to return directly the only child found?
有没有办法直接返回找到的唯一孩子?
1 个解决方案
#1
0
You can try below aggregation query.
您可以尝试以下聚合查询。
$match
to only consider documents where there is atleast one element in array matching input criteria.
$ match只考虑匹配输入条件的数组中至少有一个元素的文档。
$filter
array on the input criteria and $arrayElemAt
to project the single matched element.
$ filter数组在输入条件上,$ arrayElemAt用于投影单个匹配元素。
context.parents.aggregate([
{"$match":{
_id: mongoose.Types.ObjectId(args.parentId),
"children._id":mongoose.Types.ObjectId(args.childId)
}},
{"$project":{
"_id":0,
"children":{
"$arrayElemAt":[
{"$filter":{
"input":"$children",
"as":"child",
"cond":{"$eq":["$$child._id",mongoose.Types.ObjectId(args.childId)]}
}},
0]
}
}}
])
#1
0
You can try below aggregation query.
您可以尝试以下聚合查询。
$match
to only consider documents where there is atleast one element in array matching input criteria.
$ match只考虑匹配输入条件的数组中至少有一个元素的文档。
$filter
array on the input criteria and $arrayElemAt
to project the single matched element.
$ filter数组在输入条件上,$ arrayElemAt用于投影单个匹配元素。
context.parents.aggregate([
{"$match":{
_id: mongoose.Types.ObjectId(args.parentId),
"children._id":mongoose.Types.ObjectId(args.childId)
}},
{"$project":{
"_id":0,
"children":{
"$arrayElemAt":[
{"$filter":{
"input":"$children",
"as":"child",
"cond":{"$eq":["$$child._id",mongoose.Types.ObjectId(args.childId)]}
}},
0]
}
}}
])