mongodb - mongodb:如何将特定字段从一个集合移动到另一个集合?
问题描述
我需要将 users,allocatedHours,_id 字段从 workname 集合中分离出来,以将其插入到 workstat 集合中。
db.workname.find().pretty()
{
"_id":ObjectId("5d9fd8773d598088d2ea5e49")
"role" : "Developer",
"status" : "New",
"title" : "CountySales",
"desc" : "<p>Countysales</p>",
"allocatedHours" : 480,
"priority" : "Medium",
"reqType" : "New",
"users" : {
"assigned" : [
{
"isStatus" : "active",
"assignedDate" : ISODate("2020-11-16T12:24:56Z"),
"userId" : ObjectId("5d9fd8773d598088d2ea5e49"),
}
],
"follower" : [
{
"isStatus" : "active",
"followerDate" : ISODate("2020-11-16T12:24:56Z"),
"userId" : ObjectId("5d9fd8773d598088d2ea5e49"),
}
],
}
}
我需要将该字段移动到 workstat 集合中。我需要在聚合查询中执行此操作。我需要为多个文档执行此操作。
db.workedstat.find().pretty()
"workId": ObjectId("5d9fd8773d598088d2ea5e49"),
"allocatedHours" : 480,
"users" : {
"assigned" : [
{
"isStatus" : "active",
"assignedDate" : ISODate("2020-11-16T12:24:56Z"),
"userId" : ObjectId("5d9fd8773d598088d2ea5e49"),
}
],
"follower" : [
{
"isStatus" : "active",
"followerDate" : ISODate("2020-11-16T12:24:56Z"),
"userId" : ObjectId("5d9fd8773d598088d2ea5e49"),
}
],
}
解决方案
会是这样的:
db.workname.aggregate([
{ $project: { users: 1, allocatedHours: 1, _id: 1 } },
{ $merge: { into: "workedstat" } }
])
推荐阅读
- sql - 使用 SQL 计算 7 天保留
- c# - 如果 linq 查询计数返回零,则返回值 1
- json - 从 Json 数组中添加最后一项
- nginx - 在 Nginx 中,如果 img 已关闭,则重定向到另一个站点
- html - Angular,创建了一个自定义管道,该管道在类中返回一个函数。不断出错
- java - 如何将任意数量的规则应用于对象(可能在无法提前确定的规则之间进行交互)?
- ios - Swift 5:为什么我的结构中的数据突然为空/无?
- java - 从另一个类添加按钮,但没有任何参数通过一个普通按钮
- flutter - 如何在 Windows 中以 html 形式查看代码覆盖率?
- java - 当对象在 main 中调用实例变量时,如何构建一个增加实例变量值的方法?