skip to Main Content

I am having issues with projecting some fields with mongodb $project

my colection has the following datas

[{num:"SI-0101",mob:6289141515},...]

and my $project query

[{
  $project: {
    "Id No.": "$num",
    "Mobile No.": "$mob" // note on that ., i need it in o/p
  }
}]

When I execute this, it raise error says Field path not ends with .

How I resolve this ?

2

Answers


  1. MongoDb does not support keys that end with a dot (.). You can edit it in your code after the query. For example:

    const userRes = await userModel.findOne({num:"SI-0101"}, {num: 1, mob: 1}).lean();
    return {'Id No.': userRes.num, 'Mobile No.': userRes.mob}
    
    Login or Signup to reply.
  2. You can use $setField to achieve such behaviour if you are using MongoDB v5.0+

    db.collection.aggregate([
      {
        $replaceWith: {
          $setField: {
            field: "Id No.",
            input: "$$ROOT",
            value: "$num"
          }
        }
      },
      {
        $replaceWith: {
          $setField: {
            field: "Mobile No.",
            input: "$$ROOT",
            value: "$mob"
          }
        }
      },
      {
        $unset: [
          "num",
          "mob"
        ]
      }
    ])
    

    Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search