mongodbsearchphrase

To find first word of a sentence in mongodb of specified size


I want to find the first word from a sentence(phrase) whose size is less than 3 letters.Is there any way i could find it? please suggest.

I have used

 .map(function(st){return st.split(" ")[0];} 

function it gives me all the first words in array format.But this is not the expected output.

{ "name" : "VAS LAYER BREED FARM PRIVATE LIMITED" }

{ "name" : "UTTARA BROILER BREED FARM PRIVATE LTD" }

{ "name" : "SAI REKHA POULTRY PRIVATE LTD" }

{ "name" : "RUHITECH NUTRITION PRIVATE LTD" }

{ "name" : "SADKAR BROILER AND AGRO FARMS PRIVATE LTD" }

{ "name" : "SADAR POULTRY PRIVATE LTD" }

From this list i need the output to print only the words: ("SAI","VAS") in the output.


Solution

  • You may perform aggregation query.

    db.collection.aggregate([
      {
        $project: {
          name: {
            $let: {
              vars: {
                first: {
                  $arrayElemAt: [
                    {
                      $split: [
                        "$name",
                        " "
                      ]
                    },
                    0
                  ]
                }
              },
              in: {
                $cond: [
                  {
                    $lte: [
                      {
                        $strLenCP: "$$first"
                      },
                      3
                    ]
                  },
                  "$$first",
                  ""
                ]
              }
            }
          }
        }
      },
      {
        $match: {
          name: {
            $ne: ""
          }
        }
      },
      {
        $group: {
          _id: null,
          name: {
            $push: "$name"
          }
        }
      }
    ])
    

    MongoPlayground