mongodb - 如何编写以下 MongoDB 查询
问题描述
假设我有以下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
)项目,但使用from the item where ?foobar
timestamp
history
timestamp
type: "foo"
如果没有type
等于的子文档foo
,则过滤掉整个文档,如果有多个type
等于的子文档,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 ]
}
}
}
}
}
}
}
])
$addFields可用于覆盖现有字段 ( foobar
)。要过滤掉所有与您的条件不匹配的子文档,您可以使用$filter(外部)。对于每个foobar
文档,您可以使用$let来定义临时变量foo
。您需要 inner$filter
获取所有history
元素 where type
isfoo
然后$arrayElemAt获取第一个。然后你只需要$gt
或$lt
应用你的比较。
对于那些没有的子文档,foo
将被undefined
返回,然后在$gt
舞台上过滤掉。
推荐阅读
- c# - 如何为 Directline 语音客户端应用添加入职贺卡?
- c# - 将字符串数组转换为字符数组
- oracle - 无法在适用于 Windows 10 的 Oracle 12c R2 中打开 PDB
- reactjs - 401 错误,API 发送空白基本身份验证
- c++ - C++:QGridLayout - 小部件之间的空白
- react-native - onPress如何根据索引做很多功能?
- android - 当我更改片段时,BottomNavigationBar 部分下降
- java - 为什么要为每个实例创建静态哈希图?
- node.js - 如何从 Cloud Functions Shell 中的快速路由器访问端点
- python - 如何对 Python 中的消息分类任务执行多项朴素贝叶斯网格搜索?