需要过滤查询以获取mongodb中的选定对象

时间:2017-11-30 12:52:38

标签: mongodb

我有以下文件。 我想回来" employeedata"仅包含那些状态为"当前"

的数组对象(家庭,学术等)
{
    "_id" : ObjectId("5a1fe7ed1e9fdd17285ac13f"),
    "createdby" : "admin",
    "details" : [ 
        {
            "_id" : ObjectId("5a1fe81f1e9fdd17285ac14a"),
            "employeedata" : {
                    "createddate" : "2017-11-30T11:13:57.290Z",
                    "family" : [ 
                        {
                            "status" : "current",                        
                            "_id" : ObjectId("5a1fe81f1e9fdd17285ac153")
                        }
                    ],                
                    "academic" : [ 
                        {
                            "status" : "archive",                        
                            "_id" : ObjectId("5a1fe81f1e9fdd17285ac159")
                        }, 
                        {
                            "status" : "current",                        
                            "_id" : ObjectId("5a1fe8a71e9fdd17285ac15d")
                        }
                    ],
                     "company" : [ 
                        {
                            "status" : "archive",                        
                            "_id" : ObjectId("5a1fe81f1e9fdd17285ac150")
                        }, 
                        {
                            "status" : "current",                      
                            "_id" : ObjectId("5a1fe88e1e9fdd17285ac15c")
                        }
                    ],
                    "other" : [ 
                        {
                            "status" : "current",                       
                            "_id" : ObjectId("5a1fe81f1e9fdd17285ac154")
                        }
                    ]
            }
        }
    ]
    "confirmed" : true,
}

1 个答案:

答案 0 :(得分:0)

您可以尝试按照过滤对象,因为它是一个复杂的对象,我们必须循环遍历整个对象并在运行时对其进行修改。

    var data = JSON.parse('{"_id":"5a1fe7ed1e9fdd17285ac13f","createdby":"admin","details":[{"_id":"5a1fe81f1e9fdd17285ac14a","employeedata":{"createddate":"2017-11-30T11:13:57.290Z","family":[{"status":"current","_id":"5a1fe81f1e9fdd17285ac153"}],"academic":[{"status":"archive","_id":"5a1fe81f1e9fdd17285ac159"},{"status":"current","_id":"5a1fe8a71e9fdd17285ac15d"}],"company":[{"status":"archive","_id":"5a1fe81f1e9fdd17285ac150"},{"status":"current","_id":"5a1fe88e1e9fdd17285ac15c"}],"other":[{"status":"current","_id":"5a1fe81f1e9fdd17285ac154"}]}}]}');

function createObject() {
    for (var obj in data.details[0].employeedata) {
        if (Array.isArray(data.details[0].employeedata[obj])) {

            data.details[0].employeedata[obj].filter(function (value, index) {
                if (value.status !== 'current') {
                    //return value;
                    data.details[0].employeedata[obj].splice(index, 1);
                }
            })
        }
    }
}