user944513
user944513

Reputation: 12729

how to query in mongodb when key have space and dot

Hi I have this type of document in my collection having space and dots

{
        "_id" : ObjectId("5d7e3fd812674c2234ff1983"),
        "Emp. No" : "ABC",
        "Emp. Name" : "DEEPAK DAHIYA",
        "Card No" : "24700",
        "Department" : "TEst",
        "Att Date" : "06-Jun-2019",
        "In Time" : "06-Jun-2019 11:10",
        "Out Time" : "06-Jun-2019 16:42",
        "Status" : "P       ",
        "Late By " : "02:10",
        "Early By " : "01:18",
        "Total Hour" : "05:32",
        "OT Hour" : "00:00",
        "Location" : "Consolidated",
        "id" : "f1758761dd4f5295d9075173e83353af"
    }

now I want to aggregate my result using aggregation. but my query not giving correct output as there is space and dot in my keys

await Dance.aggregate([
  {
    $group: {
      _id: '$["Emp. No"]',
      data: {
        $addToSet: { attendance: "$['Att Date']", Status: "$Status", id: "$id" }
      }
    }
  },
  { $project: { '["Emp. No"]': "$_id", _id: 0, data: 1 } }
]);

Already tried square brackets but not working.

updated query:

const result = await Dance.aggregate([
  {
    $group: {
      _id: "$Emp. No",
      data: {
        $addToSet: { attendance: "$Att Date", Status: "$Status", id: "$id" }
      }
    }
  },
  { $project: { "Emp. No": "$_id", _id: 0, data: 1 } }
]);

not working correctly either

Upvotes: 0

Views: 1658

Answers (2)

Matt Oestreich
Matt Oestreich

Reputation: 8528

You can have fields with spaces as well as fields with underscores - you just CANNOT have fields with periods in them, for example: escaped query and non-escaped query..

Now, there are caveats with this.. As long as you're using Mongo 3.6+ and as long as the field containing a period is not a top level field, and is the only 'nested' field, it will work.. If you try to use more than one nested field, it will not work..

You can read more on the subject here...

All in all, you should just play it safe and remove the periods, but you can keep the spaces as they are allowed.

Upvotes: 1

Ikechukwu Eze
Ikechukwu Eze

Reputation: 3131

Field names cannot contain . dots or null characters and must not start with a $ dollar sign.

More Here - https://arkusnexus.com/2016/09/12/coding-guidelines-mongodb/

Upvotes: 0

Related Questions