Home > Back-end >  Converting string to Array (Aggregate mongodb)
Converting string to Array (Aggregate mongodb)

Time:05-11

Im getting random data from my database using the aggregate but apparently some of them have their genre values in string not in array, How can i convert those random data genre from string to array?

const book = await Book.aggregate([
       /* This is just for testing which books has genres in specific type
       { 
        $match: { genre: { $type: "string" } } 
       },
       */
 
      {   
        $sample: { size: 6 } 
      }
]);

sample data result(genres that are in type of string)

[
    {
        "_id": "62710ac63ad1bfc6d17030fe",
        "title": "Birth of a Theorem",
        "author": "Villani, Cedric",
        "genre": "mathematics",
        "publisher": "Bodley Head",
        "dateOfPublication": "2002-02-28T00:00:00.000Z",
        "noOfCopies": 16,
        "type": "Book",
        "form": "Non-fiction",
        "isbn": "979-81202-479229-867673-6",
        "dateAdded": "2002-11-28T00:00:00.000Z"
    },
    {
        "_id": "62710ac63ad1bfc6d1703108",
        "title": "All the President's Men",
        "author": "Woodward, Bob",
        "genre": "history",
        "publisher": "Random House",
        "dateOfPublication": "2018-02-19T00:00:00.000Z",
        "noOfCopies": 56,
        "type": "Book",
        "form": "Non-fiction",
        "isbn": "978-41428-6606587-937631-",
        "dateAdded": "2011-02-23T00:00:00.000Z"
    },
]

sample data result(genres that are in type of array)

[
    {
        "_id": "62710ac63ad1bfc6d17030be",
        "title": "Superfreakonomics",
        "author": "Dubner, Stephen",
        "genre": [
            "economics",
            "computer_science"
        ],
        "publisher": "HarperCollins",
        "dateOfPublication": "2003-10-06T00:00:00.000Z",
        "noOfCopies": 31,
        "type": "Thesis",
        "form": "Non-fiction",
        "isbn": "978-35029-7186192-465859-7",
        "dateAdded": "2009-02-12T00:00:00.000Z"
    }
]

CodePudding user response:

$sample is for documents instead of embedded array.

Update

db.collection.update({
  genre: {
    $type: "string"
  }
},
[
  {
    $set: { genre: [ "$genre" ] }
  }
],
{
  multi: true
})

mongoplayground


Aggregate

db.collection.aggregate([
  {
    $match: {
      genre: {
        $type: "string"
      }
    }
  },
  {
    $set: {
      genre: {
        $cond: {
          if: { $eq: [ { $type: "$genre" }, "string" ] },
          then: [ "$genre" ],
          else: "$genre"
        }
      }
    }
  }
])

mongoplayground

  • Related