将字符串转换为数组(聚合 mongodb)

Converting string to Array (Aggregate mongodb)

我使用聚合从我的数据库中获取随机数据,但显然其中一些数据的类型值是字符串而不是数组,我如何将这些随机数据类型从字符串转换为数组?

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

示例数据结果(字符串类型的流派)

[
    {
        "_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"
    },
]

示例数据结果(数组类型中的流派)

[
    {
        "_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"
    }
]

$sample 用于文档而不是嵌入式数组。

更新

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

mongoplayground


汇总

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

mongoplayground