简体   繁体   English

如何使用mongodb查询返回数组中不可用的给定输入值

[英]How to return the given input values not available in array using mongodb query

I am having one input arrays,EX: let UPID = ["0","1","10"] . 我有一个输入数组,例如: let UPID = ["0","1","10"] i have to check members.regularStudent whether given input values available or not ?, suppose not available means i have to push one array and return the results 我必须检查members.regularStudent是否可以给定输入值?,假设不可用意味着我必须推送一个数组并返回结果

My documents: 我的文档:

{
    "_id" : "5bb20d7556db6915846da67f",
    "members" : {
        "regularStudent" : [
            "3",
            "4"
        ]
    }
},

{
    "_id" : "5bb20d7556db6915846da55f",
    "members" : {
        "regularStudent" : [
            "1",
            "2"
        ]
    }
}

My Expected Output 我的预期输出

    [
        "0",
        "10"
    ]

My Code: 我的代码:

    let UPID = ["0","1","10"]
db.Groups.find(
    /*{
    "members.regularStudent": { $nin: UPIDs }
    }*/
)
.forEach(function(objects){
    print(objects)
})

I had updated mycode , kindly see top on my question section, print(objects) means i am having the my objects, based on this variable can you update your answer, 我已经更新了mycode ,请参见我的问题部分的顶部, print(objects)表示我拥有我的对象,根据此变量,您可以更新答案,

** print(objects) ** **打印(对象)**

{
    "_id" : "5bb20d7556db6915846da67f",
    "members" : {
        "regularStudent" : [
            "3",
            "4"
        ]
    }
},

{
    "_id" : "5bb20d7556db6915846da55f",
    "members" : {
        "regularStudent" : [
            "1",
            "2"
        ]
    }
}

You could use map method in combination with filter . 您可以将map方法与filter 结合使用。

 let UPID = ["0","1","10"]; let docs = [{ "_id" : "5bb20d7556db6915846da67f", "members" : { "regularStudent" : [ "3", "4" ] } }, { "_id" : "5bb20d7556db6915846da55f", "members" : { "regularStudent" : [ "1", "2" ] } }] let ids = [].concat(...docs.map(elem => elem.members.regularStudent)); console.log(UPID.filter(id => !ids.includes(id))); 

Here I use forEach to iterate through the data to get all of the regularStudent data into one array then use filter to filter out the data from UPID array. 在这里,我使用forEach遍历数据,以将所有RegularStudent数据收集到一个数组中,然后使用过滤器从UPID数组中过滤出数据。

 const UPID = ["0", "1" , "10"] let data = [ { "_id" : "5bb20d7556db6915846da67f", "members" : { "regularStudent" : [ "3", "4" ] } }, { "_id" : "5bb20d7556db6915846da55f", "members" : { "regularStudent" : [ "1", "2" ] } } ] let resularStudents = [] data.forEach(d => { d.members.regularStudent.forEach(rs => { resularStudents.push(rs) }) }) var result = UPID.filter( function(d) { return this.indexOf(d) < 0; }, resularStudents ); console.log(result); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM