0

have a collection with data


date_new:Array


Using mongodb aggregation how to convert into string like this, if there is a empty string convert it into " "



date_new:Array
    0: " "

2
  • can you show me an output from your collection in json? Commented Jan 14, 2020 at 13:09
  • @theUnknown : Please check the answer below, I've few question, date_new : [0:'', 1:''], So it has to be an array of objects date_new : [ {0:' '},{ 1:' '} ] or with object & it's elements like below result. Also what do you mean by if there is a empty string convert it into " " ?? We're converting array how come there will be empty string ? Do you mean an element in date_new as empty string ? Commented Jan 14, 2020 at 21:24

1 Answer 1

1

Please try this :

db.yourCollectionName.aggregate([{
    $addFields:
    {
        date_new: {
            $arrayToObject:
            {
                $map:
                {
                    input: "$date_new",
                    as: "each",
                    in: [{ $toString: { $indexOfArray: ["$date_new", '$$each'] } }, '$$each']
                }
            }
        }
    }
}])

Collection Data :

/* 1 */
{
    "_id" : ObjectId("5e1e2a74d3c98f2a7100fd44"),
    "date_new" : [ 
        "abc", 
        "def", 
        ""
    ]
}

/* 2 */
{
    "_id" : ObjectId("5e1e2f25d3c98f2a7100fd45"),
    "date_new" : []
}

Result :

/* 1 */
{
    "_id" : ObjectId("5e1e2a74d3c98f2a7100fd44"),
    "date_new" : {
        "0" : "abc",
        "1" : "def",
        "2" : ""
    }
}

/* 2 */
{
    "_id" : ObjectId("5e1e2f25d3c98f2a7100fd45"),
    "date_new" : {}
}
Sign up to request clarification or add additional context in comments.

Comments

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.