我正在使用 Mongoose 构建 Node-Js 应用程序,我的问题是:有没有办法从文档返回匹配的对象而不是整个对象,更具体地说我想返回包含日期 < 的 company_report 于 2018-06-10 这是我的代码示例:
[
{
companyName: "example",
"history": [
{
"company_report_result": [
{
"attribut": 1111,
}
],
"date": ISODate("2018-06-06T08:11:00.000Z")
},
{
"company_report_result": [
{
"attribut": 22222,
}
],
"date": ISODate("2018-06-12T08:11:00.000Z")
},
{
"company_report_result": [
{
"attribut": 3333,
}
],
"date": ISODate("2018-06-07T08:11:00.000Z")
}
]
}
]
<小时/>
查询:
Campaign.find({ 'table.history.date': { $gt: new Date('2018-06-10') } })
最佳答案
您需要使用$filter aggregation 运算符仅给出数组中匹配的元素并转义其他元素
db.collection.aggregate([
{
$match: {
"history.date": {
$gte: new Date('2018-06-10')
}
}
},
{
$project: {
companyName: 1,
history: {
$filter: {
input: "$history",
as: "hist",
cond: {
$gte: [
"$$hist.date",
new Date('2018-06-10')
]
}
}
}
}
}
])
以上查询将返回
[
{
companyName: "example",
"history": [
{
"company_report_result": [
{
"attribut": 22222,
}
],
"date": ISODate("2018-06-12T08:11:00.000Z")
}
]
}
]
关于node.js - 仅返回文档中匹配的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50803451/