繁体   English   中英

将字符串转换为数组(聚合 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
})

mongo游乐场


总计的

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

mongo游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM