MongoDB 聚合 - 重新映射内部文档
MondoDB aggregation - remapping inner documents
如何在以下示例中像这样重新映射内部文档:
db.customers.aggregate(
[
{
$project: {
"_id": 0,
"First Name": "customerDetails.firstName",
"Last Name": "customerDetails.lastName",
"Full Name": { $concat : [ "customerDetails.firstName", " ", "customerDetails.lastName" ] }
}
}
]
)
像这样放置 $ "$customer.firstName" 不起作用,而不是采用内部字段的值 firstName 基本上它没有 return 任何东西。
客户集合的结构示例:
{
"_id" : ObjectId("5fb3c41454742e0d3c9f7605"),
"customerDetails" : {
"firstName" : "Robert",
"lastName" : "Green",
"phoneNumber" : "0878712375",
"email" : "robert.green@gmail.com"
}
}
预期结果:
{
"First Name": "Robert",
"Last Name": "Green",
"Full Name": "Robert Green"
}
实际结果:
{
"First Name": "customerDetails.firstName",
"Last Name": "customerDetails.lastName",
"Full Name": "customerDetails.firstName customerDetails.lastName"
}
用 $
引用字段,应该有效:
db.customers.aggregate(
[
{
$project: {
"_id": 0,
"First Name": "$customerDetails.firstName",
"Last Name": "$customerDetails.lastName",
"Full Name": { $concat : [ "$customerDetails.firstName", " ", "$customerDetails.lastName" ] }
}
}
]
如何在以下示例中像这样重新映射内部文档:
db.customers.aggregate(
[
{
$project: {
"_id": 0,
"First Name": "customerDetails.firstName",
"Last Name": "customerDetails.lastName",
"Full Name": { $concat : [ "customerDetails.firstName", " ", "customerDetails.lastName" ] }
}
}
]
)
像这样放置 $ "$customer.firstName" 不起作用,而不是采用内部字段的值 firstName 基本上它没有 return 任何东西。
客户集合的结构示例:
{
"_id" : ObjectId("5fb3c41454742e0d3c9f7605"),
"customerDetails" : {
"firstName" : "Robert",
"lastName" : "Green",
"phoneNumber" : "0878712375",
"email" : "robert.green@gmail.com"
}
}
预期结果:
{
"First Name": "Robert",
"Last Name": "Green",
"Full Name": "Robert Green"
}
实际结果:
{
"First Name": "customerDetails.firstName",
"Last Name": "customerDetails.lastName",
"Full Name": "customerDetails.firstName customerDetails.lastName"
}
用 $
引用字段,应该有效:
db.customers.aggregate(
[
{
$project: {
"_id": 0,
"First Name": "$customerDetails.firstName",
"Last Name": "$customerDetails.lastName",
"Full Name": { $concat : [ "$customerDetails.firstName", " ", "$customerDetails.lastName" ] }
}
}
]