MongoDB 名称中包含空格的字段的 $project

MongoDB $project for field with spaces in the name

我有一个这样的文档:

{
    "_id" : NumberLong(111603),
    "max" : "Created At",
    "document" : {
        "_id" : ObjectId("54ad61013e016de5798c0582"),
        "testfield1" : "ISUZU (GM)",
        "Model - Range" : "N-series",
        "testfield2" : "N NQR 75",
    }
}

我想汇总包含许多此类文档的集合。我在 $project 步骤中遇到 "Model - Range" 的问题。 目前我正在使用

db.AE.aggregate([
    {"$project":{
        "Make":"$document.testfield1",
        "Model":"$document.testfield2",
        "_id":0, 
        "Group": "$document['Model - Range']"
     }}
]);

但由于某些原因,MongoDB 完全忽略了组字段,只添加了其他两个字段。

在 MongoDB 聚合框架中投影时,有没有办法解决其中包含 spaces/special 个字符的字段?

您可以对该字段使用普通的点表示法:

db.AE.aggregate([
    {"$project":{
        "Make":"$document.testfield1",
        "Model":"$document.testfield2",
        "_id":0, 
        "Group": "$document.Model - Range"
     }}
]);

但我同意 Neil 的观点,如果可能,应避免使用空格的字段名称。