1

I'm trying to convert array elements to new lines in the document, but I always get null values That's what I have now.

{
"_id" : ObjectId("5af9a044db06595c4a3c60d3"),
"word" : [ 
    "1501143005", 
    "41D44F7F-D5B3-4f3f-85AC-1E122DA8C506", 
    "4100", 
    "7493"
]}

Here's what I'm trying to get

{
"_id" : ObjectId("5af9a044db06595c4a3c60d3"),
"newId" : "1501143005-4100",
"oldId" : "7493-4100"}   

So far I have come to the next construction

db.getCollection('buffer2').aggregate([

    { 
       $project:{
          word:{
              "$map":{
                  "input": "$word", "as" : "u",
                  "in":{
            newId: { $concat: [ "$$u.0", "-", "$$u.2" ] },
            oldId: { $concat: [ "$$u.3", "-", "$$u.2" ] } 
           }
           }
       }}
       }]);

I would be grateful for help

0

1 Answer 1

0

You can go with $concat and $arrayElemAt instead of $map

db.collection.aggregate([
  {
    $project: {
      newId: {
        $concat: [
          {
            $arrayElemAt: [
              "$word",
              0
            ]
          },
          "-",
          {
            $arrayElemAt: [
              "$word",
              2
            ]
          }
        ],

      },
      oldId: {
        $concat: [
          {
            $arrayElemAt: [
              "$word",
              3
            ]
          },
          "-",
          {
            $arrayElemAt: [
              "$word",
              2
            ]
          }
        ],

      }
    }
  }
])

output

{
  "_id" : ObjectId("5af9a044db06595c4a3c60d3"),
  "newId" : "1501143005-4100",
  "oldId" : "7493-4100"
}   

see the result here

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

1 Comment

Thanks, it works

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.