简体   繁体   中英

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"] . 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

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,

** print(objects) **

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

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

You could use map method in combination with 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.

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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