在mongodb中查找后无法访问日期值


Main Collection
{
"_id": ObjectID("5ea1a07bfd7e4965408a5171"),
"data": [],
"history_id": ObjectID("5e4e755b380054797d9db627"),
"sender_id": ObjectID("5e4e74eb380054797d9db623"),
"text": "Hi tester",
"date": 1587650683434
}
History collection
{
"_id": ObjectID("5ea1afd4f4151402efd234e3"),
"user_id": [
"5e4a8d2d3952132a08ae5764"
],
"dialog_id": ObjectID("5e4e755b380054797d9db627"),
"date": 1587549034211,
"__v": 1
}
const messages = await MainModal.aggregate([
{
$lookup: {
from: 'history',
localField: 'history_id',
foreignField: 'history_id',
as: 'History'
}
},
{ $unwind: '$History' },
{ "$match" : { date: {$gt: "History.date" } } }, // this is not working
])

我在$history中获取值,但能够获取匹配的记录。我不知道为什么我在某个地方读到$gt对数字有效我的日期是数字太

当我设置字符串而不是"History.date"时,它确实有效,但在放入后,它不起作用

基本上,我的想法是不显示那些date是历史集合中的$lt并且用户不在5e4a8d2d3952132a08ae5764中的值

您将查询语言与聚合运算符混合在一起。为了使用$match来比较同一文档中的两个字段,您需要将$expr与聚合运算符一起使用。

对于最后的比赛阶段,使用

{ "$match":{ "$expr":{ "$gt":[ "$date", "$History.date" ] } } }

编辑

在其他字段之间添加额外的比较需要使用$and$or,如:

{ "$match":{ 
"$expr":{ 
"$and":[
{"$gt":[ "$date", "$History.date" ] },
{"$not": {"$eq":[ "$sender_id", "$History.user_id" ]}}
]
} 
}}

游乐场

最新更新