mongodb - 如何使用 $groupby 和转换不同的值 mongodb
问题描述
如何使用$if $else
groupby 条件 MongoDB 转换数据?
这个操场应该返回两个属于“tester 2”和“tester 3”文本的对象,如果我在历史集合中有多个对象,它还应该检查最后一个对象,而不是所有对象如何可能
所以条件应该说如果历史的日期是$gt
那么主集合不应该返回任何其他返回匹配的标准数据。
db.main.aggregate([
{
$lookup: {
from: "history",
localField: "history_id",
foreignField: "history_id",
as: "History"
}
},
{
$unwind: "$History"
},
{
"$match": {
$expr: {
$cond: {
if: {
$eq: [
"5e4e74eb380054797d9db623",
"$History.user_id"
]
},
then: {
$and: [
{
$gt: [
"$date",
"$History.date"
]
},
{
$eq: [
"5e4e74eb380054797d9db623",
"$History.user_id"
]
}
]
},
else: {}
}
}
}
}
])
解决方案
如果我对您的理解正确,这就是您要执行的操作:
db.main.aggregate([
{
$lookup: {
from: "history",
let: {
main_history_id: "$history_id",
main_user_id: { $toString: "$sender_id" }
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: [
"$history_id",
"$$main_history_id"
]
},
{
$eq: [
"$user_id",
"$$main_user_id"
]
}
]
}
}
}
],
as: "History"
}
},
{
$unwind: {
path: "$History",
preserveNullAndEmptyArrays: true
}
},
{
$sort: {
_id: 1,
"History.history_id": 1,
"History.date": 1
}
},
{
$group: {
_id: "$_id",
data: { $last: "$$ROOT" },
History: { $last: "$History" }
}
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$data",
{ History: "$History" }
]
}
}
},
{
"$match": {
$expr: {
$or: [
{
$eq: [
{ $type: "$History.date" },
"missing"
]
},
{
$ne: [
"5e4e74eb380054797d9db623",
"$History.user_id"
]
},
{
$and: [
{
$eq: [
"5e4e74eb380054797d9db623",
"$History.user_id"
]
},
{
$gte: [
"$date",
"$History.date"
]
}
]
}
]
}
}
}
])
推荐阅读
- java - byte[] 可以转换成连续的输入流
- angular - Ngx-Indexed-db - 数据未保存在 Microsoft Edge 浏览器中,引发数据错误
- python - 如果未找到元素,脚本将不起作用
- c# - 流未打开以供阅读
- php - Sendinblue SMTP 在 CodeIgniter 中不起作用
- regex - jflex正则表达式除零以外的任何数字
- kubernetes - 如何在 Keycloak 启动时添加/修改 LDAP 用户联合
- python - 在一个 pandas 数据框中加载一个文件夹的多个带有密码的 zip 文件
- c# - 403 仅在部署时禁止重新验证
- python - 在 python 中读取文本文件时,如何解决此列表索引超出范围错误?