在 MongoDB 中是否有任何方法可以在单个数据库查询中专门查询数组中最后一个对象的键值。
例如:这是我的集合中的文档。
{
"com" : [
{ "ts" : 1510830164203, "com" : "com1" },
{ "ts" : 1511242569673, "com" : "connected" },
{ "ts" : 1511244832741, "com" : "vb" }
],
"status" : [
{ "ts" : 1510857000000, "stat" : 3 }
]
}
正如您所看到的,com 中有多个对象。 我如何查询最后一个对象的 ts(timestamp) 或者我想检查最后一个 com 是否插入在今天的日期之间。
我已经经历过这个link.但没有找到合适的解决方案。
如有任何帮助,我们将不胜感激。
最佳答案
您可以使用$arrayElemAt
获取最后一个元素,然后在聚合
中应用匹配。要使用 $arrayElemAt
获取最后一个元素,请使用第二个值 -1
来指示数组的最后一个元素。 $arrayElemAt: ["arrayName", -1]
。代码就像
db.collectionName.aggregate([
{
$project: {
status: 1,
com: {$arrayElemAt: ["$com", -1]}
}
},
{
$match: {"com.ts": 15115465465}
}
])
注意:如果您想比较小于或大于,请使用:$lt、$lte、$gt 或 $gte
您需要的任何一个
$match: {"com.ts": {$lt: 15115465465}}
关于javascript - MongoDB - 查询数组的最后一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47407136/