[英]execMatch only returning first result
我正在尝试查找特定记录(ID为1
),然后仅返回其history
字段。 此history
字段是具有timestamp
属性的对象数组。 当我返回此历史记录字段时,我希望它仅包含timestamp
属性大于0
对象。
样品采集
[{
"_id" : 1,
"history" : [
{
"content" : "hello",
"timestamp" : 1394639953878,
"_id" : ObjectId("53208451767743b748ddbd7d")
},
{
"content" : "world",
"timestamp" : 1394639953879,
"_id" : ObjectId("33208451767743b748ddbd7e")
}
]
}]
因此,根据Mongo和Mongoose文档,我可以执行以下操作:
model.find({_id: 1})
.select({ history: { $elemMatch: { timestamp: { $gt: 0 } } } });
问题:我知道将只有一个结果(因为我选择了id 1
),但是我正在使用$elemMatch
来填充其history
字段中所有时间戳大于0
。 问题是history
只有一个物体。
$ elemMatch投影仅返回满足条件的第一个匹配元素。 查看文档 。
使用聚合将是实现您想要的正确方法。 请看下面:
db.bar.aggregate([
{$match:{_id:1}},
{$unwind:"$history"},
{$match:{"history.timestamp":{$gt:0}}},
{$group:{_id:"$_id", history:{$push:"$history"}}}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.