1

I have the following MongoDB objects which I have first transformed into key-value k-v pairs using $objectToArray and $split. How do I remove the empty string "" from the value v array? Thanks!

{ 
    "_id" : ObjectId("5e9ecf782980434d78120a49"), 
    "data_kv" : [ { "k" : "U1", "v" : [ "", "", "University", "", "", "of", "", "", "Australia", "", "" ] } ] 
}
{   
    "_id" : ObjectId("5e9ecf7f2980434d78120a4a"), 
    "data_kv" : [ { "k" : "U2", "v" : [ "", "", "University", "of", "", "", "", "", "Australia", "", "" ] } ] 
}
{ 
    "_id" : ObjectId("5e9ecf8a2980434d78120a4b"), 
    "data_kv" : [ { "k" : "U3", "v" : [ "", "", "University", "", "", "of", "", "", "", "Sweden", "", "" ] } ] 
}

1 Answer 1

1

You can use below aggregation

db.collection.aggregate([
  { $project: {
    data_kv: {
      $map: {
        input: "$data_kv",
        as: "kv",
        in: {
          k: "$$kv.k",
          v: {
            $filter: {
              input: "$$kv.v",
              cond: { $ne: ["$$this", ""] }
            }
          }
        }
      }
    }
  }}
])

MongoPlayground

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Ashh another great answer by you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.