【问题标题】:MongoDB query to get field that has string arrayMongoDB查询以获取具有字符串数组的字段
【发布时间】:2021-07-20 16:10:57
【问题描述】:

我正在使用数据集

https://raw.githubusercontent.com/rashida048/Datasets/master/movie_dataset.csv

我需要下面的

  1. 排名前 5 的制作公司列表(按预算)并列出他们最受欢迎的 5 部电影、收入和平均票数。

  2. 2000-2016年每年发行电影数量最多的制作公司列表。

但是,当我查询 production_companies 字段时,数据看起来有点奇怪。想知道我的导入是否不正确。不知道我如何才能得到上述问题的结果。

db.movie_dataset.find({}, {'production_companies' : 1 , '_id' : 0 }).limit(2).pretty();
{
    "production_companies" : "[{\"name\": \"Walt Disney Pictures\", \"id\": 2}, {\"name\": \"Jerry Bruckheimer Films\", \"id\": 130}, {\"name\": \"Second Mate Productions\", \"id\": 19936}]"
}
{
    "production_companies" : "[{\"name\": \"Ingenious Film Partners\", \"id\": 289}, {\"name\": \"Twentieth Century Fox Film Corporation\", \"id\": 306}, {\"name\": \"Dune Entertainment\", \"id\": 444}, {\"name\": \"Lightstorm Entertainment\", \"id\": 574}]"
}

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    我检查了 csv,它看起来标题没有被命名为被标记为嵌入文档。

    要作为嵌入文档导入,标题应在csv中标记为production_companies.nameproduction_companies.id。这就是这里没有提到的方式。因此,在导入期间,字段 production_companies 已作为字符串导入。

    您可以在 csv 中正确设置标头,然后在 mongo shell 中使用以下代码导入或更新 production_companies 字段。

    对于 mongosh v5.0

    db.movies.find({}).forEach((d) => { 
        db.movies.updateOne({ _id: d._id }, 
           { $set: { production_companies: JSON.parse(d.production_companies) } });
     })
    

    适用于 mongo shell v4.4

    cursor = db.collection.find();
    while ( cursor.hasNext() ) {
       var d = cursor.next();
       db.movies.updateOne({ _id: d._id }, 
           { $set: { production_companies: JSON.parse(d.production_companies) } 
    }
    

    Documentation

    【讨论】:

    • 我正在使用MongoDB shell version v4.4.0。收到语法错误uncaught exception: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data : @(shell):3:40 DBQuery.prototype.forEach@src/mongo/shell/query.js:512:9
    • 代码:db.movie_dataset.find({}).forEach((d) => { db.movie_dataset.updateOne({ _id: d._id }, { $set: { production_companies: JSON.parse(d.production_companies) } }); });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 2013-05-16
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多