首页 > 解决方案 > 如何创建查询以从 json 字符串中获取记录

问题描述

我正在使用 mongodb,我们的数据在 json 格式键值对中,我有一个关键的追随者人口统计数据,它的值是 json 字符串格式。我想根据这个字符串获取记录:

"followerDemographics":"{\"topfollowerDemographybyCities\":{\"Riau\":3.45,\"Jawa Timur\":6.9,\"Jawa Barat\":31.03,\"Daerah Khusus Ibukota Jakarta\":6.9,\"Others\":48.28,\"Uttar Pradesh\":3.45},\"topfollowerDemographybyCountry\":{\"India-IN\":6.9,\"Philippines-PH\":3.45,\"Malaysia-MY\":3.45,\"Indonesia-ID\":82.76,\"United States-US\":3.45,\"Others\":0},\"InstagramId\":\"192198926\",\"gender\":{\"male\":26.246719160104988,\"female\":73.75328083989501}}"

我已经尝试过了:

     // Gender Ratio
      if (genderRatio === 'Male') {
         Influencer.find({}, async(err, influecner) => {
         const Influecner = influecner.map(async repo => {
           if(repo.followerDemographics){
            var x = repo.followerDemographics;
            x = x.replace(/\\"/g, '"');
            return {
                '_id':repo._id,
                'followerDemographics': JSON.parse(x)
              }
           }
          });
          Promise.all(Influecner).then((list) => {
            console.log(list, 'infinfinf');
          });

        });
        genderRatioQuery = {
          $and: [{ 'followerDemographics.gender.male': { $gte: parseInt(req.query.minGenderRatio) } },
            { 'followerDemographics.gender.male': { $lte: parseInt(req.query.maxGenderRatio) }} ],
        };
      }

这是收藏的一部分

"followerDemographics":"{\"topfollowerDemographybyCities\":{\"Riau\":3.45,\"Jawa Timur\":6.9,\"Jawa Barat\":31.03,\"Daerah Khusus Ibukota Jakarta\":6.9,\"Others\":48.28,\"Uttar Pradesh\":3.45},\"topfollowerDemographybyCountry\":{\"India-IN\":6.9,\"Philippines-PH\":3.45,\"Malaysia-MY\":3.45,\"Indonesia-ID\":82.76,\"United States-US\":3.45,\"Others\":0},\"InstagramId\":\"192198926\",\"gender\":{\"male\":26.246719160104988,\"female\":73.75328083989501}}"

我有一个搜索过滤器,我想在其中根据性别比例获取记录。假设当我们单击男性并将范围设置为 20% 到 70% 时,我想获取所有 blongs 到 20 到 70 的记录

标签: mongodb

解决方案


我不确定我是否理解您在代码中使用的技术,但如果您编写 MongoDB JS 脚本,它看起来类似于以下内容。

假设您的数据库名称是geo_data并且您的集合是influencer然后使用 MapReduce 函数的代码将如下所示:

var _db = db.getSiblingDB("geo_data");

// Parsing JSON field and filtering items we only need
mapFunc = function() {
    parsed = JSON.parse(this.followerDemographics);
    if (parsed.gender.male > 20 && parsed.gender.male < 70) {
        emit(this._id, this);
    }
}

// Returning all items
reduceFunc = function(id, items) {
    return { "result": items };
}

// Performing mapReduce here and the output will be in collection named `result`.
_db.influencer.mapReduce(mapFunc, reduceFunc, { out: "result" });

// Result collection in your db now contains all items filtered as you need
var items = _db.result.find();

// Showing result for testing purposes
items.forEach(function(x){
    print("Item: ");
    printjson(x)
});

希望这可以帮助。


推荐阅读