我正在努力寻找一种更整洁的方法来做这件事。当然,我可以使用经典的if- call条件来完成它,但是我想以某种方式将它委托给mongodb,并使用单个db调用来实现它。我使用节点js和本地mongo驱动程序。
基本上,我想在mongo ->中执行一个查找查询。
。
示例->使用以下几个文档
[{
id: 1,
status: 'current'
},
{
id: 2,
status: 'default'
}
]因此,在这种情况下,如果完成状态查询。如果find是以当前的状态查询的,它将用id 1获取文档。如果find是使用状态完成的查询,因为它不是作为回退出现的,它应该返回默认值。
我想我可以利用聚合来实现这一点吗?怎么做我被困在那部分了。此外,在不进行聚合的情况下,是否有可能实现它?
任何帮助都将不胜感激。谢谢!!
发布于 2022-05-02 17:16:53
根据条件有多复杂,可以在聚合中应用以下步骤:
滤波器
{
"$match": {
"$or": [
{
"status": "current"
},
{
"status": "default"
}
]
}
}评分
{
"$project": {
"id": 1,
"status": 1,
"score": {
"$switch": {
"branches": [
{
"case": {
"$eq": ["$status", "current"]
},
"then": 1
},
{
"case": {
"$eq": ["$status", "default"]
},
"then": 0
}
],
"default": -1
}
}
}
}注意开关语句中的顺序很重要,特别是当您有很多分支时。
计算一系列案例表达式。当$switch找到一个计算为true的表达式时,它会执行一个指定的表达式并从控制流中分离出来。
排序
{
"$sort": {
"status": 1
}
}极限
{
"$limit": 1
}完全管道
[
{
"$match": {
"$or": [
{
"status": "current"
},
{
"status": "default"
}
]
}
},
{
"$project": {
"id": 1,
"status": 1,
"score": {
"$switch": {
"branches": [
{
"case": {
"$eq": ["$status", "current"]
},
"then": 1
},
{
"case": {
"$eq": ["$status", "default"]
},
"then": 0
}
],
"default": -1
}
}
}
},
{
"$sort": {
"status": 1
}
},
{
"$limit": 1
}
]这是一种容易理解和易于扩展的方法,但我不知道速度。
https://stackoverflow.com/questions/72089684
复制相似问题