如何创建查询以从json字符串中获取记录

时间:2019-03-26 13:06:14

标签: mongodb

我正在使用mongodb,我们的数据位于json formate键值对中,并且我具有on键关注者人口统计信息,其值位于json字符串formate中。我想基于此字符串获取记录:

"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}}"

我有一个Serch过滤器,我想根据性别比率获取记录。假设当我们单击男性并设置20%到70%的范围时 那么我想获取所有记录,这些记录大约是20到70

1 个答案:

答案 0 :(得分:0)

我不确定我是否了解您的代码中使用了哪种技术,但是如果您编写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)
});

希望这会有所帮助。

相关问题