mongodb - 聚合MongoDB 3.4
问题描述
我有一个这样的文件集。我想更改子文档中的值
{ "cities" :[
{
"city" : "London",
"country" : "United Kingdom"
},
{
"city" : "New York",
"country" : "United States"
}
{
"city" : "San Francisco",
"country" : "United States"
}]
}
If city is San Francisco
then Sf
If city is New york
then NY
Elsenull
我用过$switch
但不起作用。我正在使用 MongoDB v3.4
。
解决方案
试试这个:
db.collection.aggregate([
{
$project: {
cities: {
$map: {
input: "$cities",
in: {
country: "$$this.country",
city: {
$switch: {
branches: [
{
case: {
$eq: [ "$$this.city","San Francisco"]
},
then: "Sf"
},
{
case: {
$eq: [ "$$this.city", "New York" ]
},
then: "NY"
}
],
default: null
}
}
}
}
}
}
}
//Uncomment this stage if aggregation result meets your requirements
//,{$out: "collection"}
])
推荐阅读
- python - 熊猫多索引列合并某些列
- python - 如何从仅日期时间的数据中绘制折线图
- javascript - 用于计算的 JavaScript 函数不起作用?
- ios - Cocoapods - FirebaseAnalytics 仅在使用 FirebaseCore 时安装
- .net-core - 为什么用类声明比结构体占用更多的内存?
- java - 获取TreeMap Java的TreeMapEntry和HashMapNode
- vue.js - VUE中的CKEditor5自定义构建
- java - MongoDB:游标在 next() 完成之前关闭
- swift - 当我将字符串格式化为日期时出现错误的日期
- ios - NSFileHandle writeData 同步延迟主线程操作