如何在返回结果中创建新字段并根据使用 Mongoose 的条件在其中设置值?
Posted
技术标签:
【中文标题】如何在返回结果中创建新字段并根据使用 Mongoose 的条件在其中设置值?【英文标题】:How can I create new fields in return results and set values in them on the basis of conditions using Mongoose? 【发布时间】:2020-12-10 06:44:52 【问题描述】:我有一个名为“Animals”的 MongoBD 集合
[
_id:ObjectId("5f3ecddd7fe1af0c68614605"),
status: "wild",
name: "Wolf"
,
_id:ObjectId("5f3ecddd7fe1af0c68614606"),
status: "domestic",
name: "Dog"
,
_id:ObjectId("5f3ecddd7fe1af0c68614607"),
status: "domestic",
name: "Pussy Cat"
,
_id:ObjectId("5f3ecddd7fe1af0c68614608"),
status: "wild",
name: "Lion"
,
_id:ObjectId("5f3ecddd7fe1af0c68614609"),
status: "wild",
name: "Snake"
]
我想在 mongoose 中使用聚合管道查询该集合,并使用一个新字段返回结果,该字段根据文档中的 status
字段对它们进行分类。例如,具有status: "wild"
的文档获取新字段new_field: "Tough Forest Animal"
然后有status: "domestic"
的文档得到新字段new_field: "Friendly Neighborhood Animal"
我想要这样的结果
[
_id: "5f3ecddd7fe1af0c68614605",
status: "wild",
name: "Wolf",
new_field: "Tough Forest Animal"
,
_id: "5f3ecddd7fe1af0c68614606",
status: "domestic",
name: "Dog",
new_field: "Friendly Neighborhood Animal"
,
_id: "5f3ecddd7fe1af0c68614607",
status: "domestic",
name: "Pussy Cat",
new_field: "Friendly Neighborhood Animal"
,
_id: "5f3ecddd7fe1af0c68614608",
status: "wild",
name: "Lion",
new_field: "Tough Forest Animal"
,
_id: "5f3ecddd7fe1af0c68614609",
status: "wild",
name: "Snake",
new_field: "Tough Forest Animal"
]
非常感谢给予我的所有帮助。谢谢
【问题讨论】:
【参考方案1】:我终于弄明白了。使用 switch 语句
AnimalsModel.aggregate([
$project:
"_id": 1,
"status": 1,
"name": 1,
"new_field":
"$switch":
"branches": [
"case": "$eq": [ "$status", "wild" ] , "then": 'Tough Forest Animal' ,
"case": "$eq": [ "$status", "domestic" ] , "then": 'Friendly Neighborhood Animal' ,
],
"default": 'None of the above'
],function (error, animals)
console.log(animals)
);
【讨论】:
以上是关于如何在返回结果中创建新字段并根据使用 Mongoose 的条件在其中设置值?的主要内容,如果未能解决你的问题,请参考以下文章
如何删除元素如何根据另一个rdd从一个rdd中删除元素并在pyspark中创建新的rdd?