mongodb - 如何创建查询以从 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 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)
});
希望这可以帮助。
推荐阅读
- c# - RestSharp Post Json 对象
- javascript - 使用 JavaScript 下载图像
- c# - SWIG C# 使用 Director =“1”传递二进制数据
- nginx - nginx docker compose 未启动并运行
- javascript - 成功验证后将表单数据发送到 .php 文件的 Ajax 代码
- python - 没有root权限时如何使用pgadmin python
- r - 如何在 Shiny 中对多个表进行排序
- python - 有没有办法在没有 pyopencl 的 amd gpu 上运行 python 脚本
- node.js - 错误:在 MERN 堆栈应用程序中,没有从渲染返回任何内容...
- c# - 在 c# 中连接两个项目(在 Navisworks 中创建插件)