skip to Main Content
Companies
[
   { _id: 1, name: "Apple" },
   { _id: 2, name: "Microsoft" },
   { _id: 3, name: "Facebook" },
   { _id: 4, name: "Tesla" }
]

Is there a way to show name filed in query to new format?

Example )

Companies.find({}).newFormat(document => name: document.name[0] + '****')


Expected Result:

[
   { _id: 1, name: "A****" },
   { _id: 2, name: "M****" },
   { _id: 3, name: "F****" },
   { _id: 4, name: "T****" }
]

2

Answers


  1. You can use aggregate like this

    db.Companies.aggregate([
      {
        $addFields: {
          name: {
            $concat: [
              { $substr: ['$name', 0, 1] }, 
              '****'
            ]
          }
        }
      }
    ])
    
    Login or Signup to reply.
  2. you can do a projection with $concat and $substr with find as well

    db.collection.find({},{
      name: { $concat: [ { $substr: [ "$name", 0, 1 ] }, "****" ]}
    })
    

    playground

    if you want to add a variable number of "*" say based on the length of each name you can use $reduce

    db.collection.aggregate([
      {
        $addFields: {
          name: {
            $reduce: {
              input: { $range: [ 1, { $strLenCP: "$name" }, 1 ] },
              initialValue: { $substr: [ "$name", 0, 1 ] },
              in: { $concat: [ "$$value", "*" ] }
            }
          }
        }
      }
    ])
    

    playground

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