Use $addFields to add a field from lookup stage without unwind

Viewed 1755

I am trying to add a field in the aggregation pipeline using $addField stage. In the below query after lookup I dont want to unwind the provider_info but want to add a field p_insensitive to be used in sort.

db.getCollection('providers').aggregate([
{"$lookup": {
    "localField":   "uid",
    "from":         "users",
    "foreignField": "_id",
    "as":           "provider_info"}},
{"$addFields": {"prov_insensitive": {"$toLower": "$provider_info.full_name"}}},
{"$sort": {"p_insensitive": 1}}

])

It is throwing following error:

can't convert from BSON type array to String

I can not use unwind stage here according to requirement.

Please help me solving this.

1 Answers

When you use "$provider_info.full_name" will return array of full_name like ["ABC"] so $toLower operator can only allow string as input,

In this situation you can try one of the option from two,

  • $arrayElemAt starting from MongoDB v3.2, returns specific element from specified index,
  {
    "$addFields": {
      "prov_insensitive": {
        "$toLower": {
          $arrayElemAt: ["$provider_info.full_name", 0]
        }
      }
    }
  }
  • $first starting from MongoDB v4.4, returns first element from array,
  {
    "$addFields": {
      "prov_insensitive": {
        "$toLower": {
          $first: "$provider_info.full_name"
        }
      }
    }
  }
Related