MongoDB仅从嵌套数组中获取匹配元素
我有这样的收藏:MongoDB仅从嵌套数组中获取匹配元素,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我有这样的收藏: { _id : 123, username : "xy", comments : [ { text : "hi", postdate : 123456789 }, { text : "hi1", postdate : 555555555 }, { text : "hi2", postdate : 666666666 }, {
{
_id : 123,
username : "xy",
comments : [
{
text : "hi",
postdate : 123456789
},
{
text : "hi1",
postdate : 555555555
},
{
text : "hi2",
postdate : 666666666
},
{
text : "hi3",
postdate : 987654321
}
]}
现在,我只想评论有后发日期555或更高和987654321或更低。我有这个查询,但它不起作用:
db.post.aggregate([
{$match : {$and : [
{"_id": ObjectId("123")},
{"comments.posttime" : {$lte : 987654321}},
{"comments.posttime" : {$gte : 555555555}}
]}}
,{$unwind: "$comments"}]).pretty();
但是当我尝试这个方法时,它会得到所有的数组元素。如何做到这一点
谢谢大家! 使用$redact限制文档的内容
db.an.aggregate([{
$redact: {
"$cond": [{
$and: [{
"$gte": [{
"$ifNull": ["$postdate", 555555555]
},
555555555
]
}, {
"$lte": [{
"$ifNull": ["$postdate", 987654321]
},
987654321
]
}]
}, "$$DESCEND", "$$PRUNE"]
}
}]).pretty()
您必须先解开注释,然后进行匹配。这样注释数组将被展平,匹配条件可以对其进行适当过滤
[{$unwind: "$comments"},{$match : {$and : [
{"_id": ObjectId("123")},
{"comments.posttime" : {$lte : 987654321}},
{"comments.posttime" : {$gte : 555555555}}
]}}]
这将为每个注释提供一行,如果您希望在数组中找到匹配的注释,请使用聚合on _id和$push注释可能重复感谢您的回答!但它不起作用。如果$gte是555,我就得不到任何元素。如果我将它设置为0,将$lte从987654321设置为6666666,我将得到完整的堆栈。对我来说,它与您的数据一起工作,$gte 0和$lte 6666666,db.an.aggregate([{$redact:{“$cond”:[{$and:[{$gte:[{$ifNull:[$postdate,0]},0]},},{$lte:[$ifNull:[$postdate,666666666]},66666]}])$$$drown},{$PRUNE},},对我犯了一个愚蠢的错误。谢谢你,这很有效!