3

I have a document that goes like this:

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

And I would like to aggregate on the collection containing a number of these documents. I'm having an issue with the "Model - Range" in the $project step. Currently I am using

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

But for some reason, MongoDB is completely ignoring the Group field and only adding the other two fields.

Is there a way to address fields with spaces/special characters in them when projecting in MongoDB aggregation framework?

6
  • Yes it's not a valid way to notate this ( it is a string and not JavaScript code you did notice ) and you really should not name fields like this. Windows taught too many of the younger generation very bad habits. We code and model with consecutiveCamelCasedNames because we have experience and we know what works and what does not. Commented Jan 9, 2015 at 13:38
  • What if I have no control over the field names, based on the mongoDB documentation, the only characters that are not accepted are "." and ones that start with "$". Commented Jan 9, 2015 at 13:44
  • It got answered. I didn't want to because you really should not name properties this way. It only results in someone coming in and fixing your code. Leave a better legacy on the world and do it right the first time. Commented Jan 9, 2015 at 13:54
  • The fields get created by an external CSV file that I do not control. The entire idea of a noSQL database is that everything should be variable..types, names, etc.. I agree that naming conventions should exist even in noSQL but in this particular case the only way to do it is to re-adjust the field names while importing (again sort of defies the idea behind noSQL) Commented Jan 9, 2015 at 13:58
  • 2
    You know you can always "map" field names in CSV imports. So there is that. Commented Jan 9, 2015 at 14:00

1 Answer 1

7

You can just use normal dot notation for that field:

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

But I agree with Neil that field names with spaces in them should be avoided, if possible.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.