
[英]Efficent MongoDB queries to get reports from one collection and insert into another
[英]MongoDB Query to get unique of particular fields from a collection and insert into another collection
我在mongodb中有一个集合。 当前有很少的条目。
样品输入:
//1
{
"_id" : ObjectId("5b52693cbb49784bc24271a9"),
"username" : "sai",
"userid": "101",
"useralias" : "scharan",
"country" : "IND",
"createdby": "sai",
"lastmodifiedby": "charan",
"lastmodifieddate": "07/20/2018 16:59"
}
//2
{
"_id" : ObjectId("5b52693cbb49784bc24271a9"),
"username" : "sai",
"userid": "102",
"useralias" : "kiran",
"country" : "IND",
"createdby": "kiran",
"lastmodifiedby": "kiran",
"lastmodifieddate": "07/21/2018 16:59"
}
首先,我要排除用户名和国家/地区以外的字段。
我正在运行此查询
db.userconfig.find({}, {_id: 0, username: 1, country: 1});
这是结果
//1
{
"username" : "sai",
"country" : "IND",
}
//2
{
"username" : "sai",
"country" : "IND",
}
由此,我想准备两个文档的唯一性并插入其他集合中。
//1
{
"username" : "sai",
"country" : "IND",
}
//2
{
"username" : "sai",
"country" : "IND",
}
在插入其他集合之前,我想添加一些其他字段(createdby,lastmodifiedby,lastmodifieddate)。 理想情况下,这应导致:
{
"username" : "sai",
"country" : "IND",
"createdby": "admin",
"lastmodifiedby": "admin",
"lastmodifieddate": "12/20/2018 12:15"
}
因为要在结果后添加其他字段,所以不能轻易使用aggregation和$ group运算符,而最好使用javascript自己做。
objects = [
{
"username" : "sai",
"country" : "IND",
}
//2
{
"username" : "sai",
"country" : "IND",
}
]
var uniqueObjects = {};
objects.forEach(function(o){uniqueObjects[hex_md5(JSON.stringify(o))]=o});
for(var i in uniqueObjects)
// Add your extra fields to each unique object and insert them into a collection using uniqueObjects[i];
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.