如何编写以下MongoDB查询
假设我有以下如何编写以下MongoDB查询,mongodb,nosql,aggregation-framework,Mongodb,Nosql,Aggregation Framework,假设我有以下foobar集合: { "foobar": [ { "_id": "abc", "history": [ { "type": "foo", "timestamp": 123456789.0 }, { "type": "bar", "timestamp": 123456789.0 } ]
foobar
集合:
{
"foobar": [
{
"_id": "abc",
"history": [
{
"type": "foo",
"timestamp": 123456789.0
},
{
"type": "bar",
"timestamp": 123456789.0
}
]
},
{
"_id": "dfg",
"history": [
{
"type": "baz",
"timestamp": 123456789.0
},
{
"type": "bar",
"timestamp": 123456789.0
}
]
},
{
"_id": "hij",
"history": [
{
"type": "foo",
"timestamp": 123456789.0
},
{
"type": "bar",
"timestamp": 123456789.0
},
{
"type": "foo",
"timestamp": 123456789.0
}
]
}
]
}
如何根据历史记录
项目中的时间戳
道具查询($gte
/$lte
)foobar
项目,但使用时间戳
从键入“foo”
的项目中查询
如果没有
类型
等于foo
的子文档,则会过滤掉整个文档,如果有多个子文档类型
等于foo
,则可以匹配任何人。您可以尝试以下聚合:
var threshold = 123456788;
db.foobar.aggregate([
{
$addFields: {
foobar: {
$filter: {
input: "$foobar",
as: "doc",
cond: {
$let: {
vars: {
foo: {
$arrayElemAt: [
{
$filter: {
input: "$$doc.history",
as: "history",
cond: {
$eq: [ "$$history.type", "foo" ]
}
}
},
0]
}
},
in: {
$gt: [ "$$foo.timestamp", threshold ]
}
}
}
}
}
}
}
])
可用于覆盖现有字段(foobar
)。要筛选出与您的条件不匹配的所有子文档,您可以使用(外部文档)。对于每个foobar
文档,您可以使用它定义临时变量foo
。您需要使用内部$filter
来获取类型为foo
的所有历史
元素,然后获取第一个元素。然后您只需要$gt
或$lt
来应用比较
对于那些没有foo
的子文档,将返回未定义的,然后在$gt
阶段将其过滤掉。如果没有类型:foo,该怎么办。那份文件应该被过滤掉吗?如果有不止一个foo呢?您能编辑您的帖子并为您的文档添加预期输出吗?谢谢。我试试看。