[英]Get precise subdocuments in document array mongoose
I'm developing a graphql API using mongoose to interact with my mongo database and I'm struggling with something. 我正在使用mongoose开发一个graphql API来与我的mongo数据库交互,我正在努力解决一些问题。 I have documents with subdocuments arrays and I need to get all the documents containing a subdocument that have a specific field value. 我有子文档数组的文档,我需要获取包含具有特定字段值的子文档的所有文档。 The problem is I want to get only this subdocument in the document. 问题是我想在文档中只获取此子文档。 It's easier to explain with an example : 用一个例子来解释更容易:
My documents are like that : 我的文件是这样的:
documents: [
{
id: 1,
items: [
{
value: 5,
},
{
value: 10,
},
]
},
{
id: 2,
items: [
{
value: 7,
},
{
value: 10,
},
]
}]
I want to get all the documents that have an item with value == 5
, but containing only this value like : 我希望获得所有具有value == 5
的项目的文档,但只包含以下值:
results : [
{
id: 1,
items: [
{
value: 5,
}
]
}]
What I do for now is : 我现在要做的是:
documents.find({
items: {
$elemMatch : {
value: { $eq: 5 }
}
},
});
The thing is doing this I get the correct document, but it contains all the items, not only the ones that match the condition. 事情是这样做我得到了正确的文件,但它包含所有项目,而不仅仅是符合条件的项目。 I looked for a solution but I didn't find anything to do so. 我找了一个解决方案,但我没有找到任何可以解决的问题。
Thanks for your help, I hope it is clear enough. 谢谢你的帮助,我希望它足够清楚。
You would need to use the aggregation framework as follows: 您需要使用聚合框架,如下所示:
db.test.aggregate(
{ $match: { "id": 1 }},
{ $unwind: '$items' },
{ $match: { "items.value": 5 }},
{ $project: { "_id": 0 }}
)
Return value: 返回值:
{ "id" : 1, "items" : { "value" : 5 } }
You need to specify the fields you want to return from the query. 您需要指定要从查询返回的字段。
documents.find({
items: {
$elemMatch : {
value: { $eq: 5 }
}
},
}, {requiredFields: 1});
See example in this question. 请参阅此问题中的示例。
Official docs: here - Search for "select" 官方文档: 这里 - 搜索“选择”
If you need to filter out the results too, you an use the $filter 如果您还需要过滤掉结果,请使用$ filter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.