mongodb 内部对象到父级别
mongodb inner object to parent level
聚合后我得到了结果
{
data: [
{
"_id": "61922aed85c74b2d1ef671bb",
"employee": {
"firstName": "fname",
"lastName": "lname",
"middleName": "mname"
},
"days": [
{
"_id": "61922aed85c74b2d1ef671be",
"day": "2021-09-01T21:00:00.000Z",
"data": {
"hours": 0,
"type": "OT",
"_id": "61922aed85c74b2d1ef671bf",
"updateDate": "2021-11-15T09:39:57.624Z"
}
},
{
"_id": "61922aed85c74b2d1ef671c0",
"day": "2021-09-02T21:00:00.000Z",
"data": {
"hours": 0,
"type": "OT",
"_id": "61922aed85c74b2d1ef671c1",
"updateDate": "2021-11-15T09:39:57.625Z"
}
}
]
}
]
}
是否可以将天数组数据的内部对象提取到父级别。
由此
{
"_id": "61922aed85c74b2d1ef671be",
"day": "2021-09-01T21:00:00.000Z",
"data": {
"hours": 0,
"type": "OT",
"_id": "61922aed85c74b2d1ef671bf",
"updateDate": "2021-11-15T09:39:57.624Z"
}
}
至此
{
"_id": "61922aed85c74b2d1ef671be",
"day": "2021-09-01T21:00:00.000Z",
"hours": 0,
"type": "OT",
"updateDate": "2021-11-15T09:39:57.624Z"
}
只需像这样使用$project
:
db.collection.aggregate([
{
"$project": {
"day": 1,
"hours": "$data.hours",
"type": "$data.type",
"updateDate": "$data.updateDate"
}
}
])
示例here
或者更新数组中的值:
db.collection.aggregate([
{
"$project": {
"_id": 1,
"employee": 1,
"days": {
"$map": {
"input": "$days",
"as": "d",
"in": {
"_id": "$$d._id",
"day": "$$d.day",
"hours": "$$d.data.hours",
"type": "$$d.data.type",
"updateData": "$$d.data.updateDate"
}
}
}
}
}
])
示例here
聚合后我得到了结果
{
data: [
{
"_id": "61922aed85c74b2d1ef671bb",
"employee": {
"firstName": "fname",
"lastName": "lname",
"middleName": "mname"
},
"days": [
{
"_id": "61922aed85c74b2d1ef671be",
"day": "2021-09-01T21:00:00.000Z",
"data": {
"hours": 0,
"type": "OT",
"_id": "61922aed85c74b2d1ef671bf",
"updateDate": "2021-11-15T09:39:57.624Z"
}
},
{
"_id": "61922aed85c74b2d1ef671c0",
"day": "2021-09-02T21:00:00.000Z",
"data": {
"hours": 0,
"type": "OT",
"_id": "61922aed85c74b2d1ef671c1",
"updateDate": "2021-11-15T09:39:57.625Z"
}
}
]
}
]
}
是否可以将天数组数据的内部对象提取到父级别。
由此
{
"_id": "61922aed85c74b2d1ef671be",
"day": "2021-09-01T21:00:00.000Z",
"data": {
"hours": 0,
"type": "OT",
"_id": "61922aed85c74b2d1ef671bf",
"updateDate": "2021-11-15T09:39:57.624Z"
}
}
至此
{
"_id": "61922aed85c74b2d1ef671be",
"day": "2021-09-01T21:00:00.000Z",
"hours": 0,
"type": "OT",
"updateDate": "2021-11-15T09:39:57.624Z"
}
只需像这样使用$project
:
db.collection.aggregate([
{
"$project": {
"day": 1,
"hours": "$data.hours",
"type": "$data.type",
"updateDate": "$data.updateDate"
}
}
])
示例here
或者更新数组中的值:
db.collection.aggregate([
{
"$project": {
"_id": 1,
"employee": 1,
"days": {
"$map": {
"input": "$days",
"as": "d",
"in": {
"_id": "$$d._id",
"day": "$$d.day",
"hours": "$$d.data.hours",
"type": "$$d.data.type",
"updateData": "$$d.data.updateDate"
}
}
}
}
}
])
示例here