MongoDB查询可从一个集合中获取特定字段的唯一性,然后插入另一个集合中

时间:2018-12-20 20:11:47

标签: mongodb

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

1 个答案:

答案 0 :(得分:1)

由于要在结果后添加其他字段,因此无法轻松使用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];
 })