从动态命名的子文档中删除字段的项目
Project to remove field from dynamically-named subdocument
我有这样的数据库结构:
{
"_id" : ObjectId("5a702c1434ddce0015a9fc2b"),
"create_on_fmt" : "20180130082556",
"create_on" : ISODate("2018-01-30T08:25:56.222Z"),
"type" : 1,
"code" : "3YFZZ",
"handled_by" : {
"644e1dd7-2a7f-18fb-b8ed-ed78c3f92c2b" : {
"email" : "abca@email.com",
"update_on" : ISODate("2018-02-05T15:43:59.612Z"),
"update_on_fmt" : "20180205154359"
}
}
}
当 644e1dd7-2a7f-18fb-b8ed-ed78c3f92c2b
是自动生成且值不完全正确时,我如何在没有 handled_by.XXX.update_on
的情况下 return 结果?
我试过db.test.find({"code" : "3YFZZ"}, {'handled_by./%/.update_on':0}).pretty()
但没有成功。
您可以使用$objectToArray to be able to use $project on this property (discarding it) and then reverse operation which is $arrayToObject恢复原状。试试这个:
db.test.aggregate([
{
$addFields: {
handled_by: {
$objectToArray: "$handled_by"
}
}
},
{
$project: {
"handled_by.v.update_on": 0
}
},
{
$addFields: {
handled_by: {
$arrayToObject: "$handled_by"
}
}
}
])
我有这样的数据库结构:
{
"_id" : ObjectId("5a702c1434ddce0015a9fc2b"),
"create_on_fmt" : "20180130082556",
"create_on" : ISODate("2018-01-30T08:25:56.222Z"),
"type" : 1,
"code" : "3YFZZ",
"handled_by" : {
"644e1dd7-2a7f-18fb-b8ed-ed78c3f92c2b" : {
"email" : "abca@email.com",
"update_on" : ISODate("2018-02-05T15:43:59.612Z"),
"update_on_fmt" : "20180205154359"
}
}
}
当 644e1dd7-2a7f-18fb-b8ed-ed78c3f92c2b
是自动生成且值不完全正确时,我如何在没有 handled_by.XXX.update_on
的情况下 return 结果?
我试过db.test.find({"code" : "3YFZZ"}, {'handled_by./%/.update_on':0}).pretty()
但没有成功。
您可以使用$objectToArray to be able to use $project on this property (discarding it) and then reverse operation which is $arrayToObject恢复原状。试试这个:
db.test.aggregate([
{
$addFields: {
handled_by: {
$objectToArray: "$handled_by"
}
}
},
{
$project: {
"handled_by.v.update_on": 0
}
},
{
$addFields: {
handled_by: {
$arrayToObject: "$handled_by"
}
}
}
])