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

时间:2019-01-09 09:39:19

标签: javascript mongodb mongodb-query

我有一个输入数组,例如:let UPID = ["0","1","10"]。我必须检查members.regularStudent是否给定输入值可用?假设不可用,则意味着我必须推入一个数组并返回结果

  

我的文档:

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

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

我的预期输出

    [
        "0",
        "10"
    ]
  

我的代码:

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

我已经更新了mycode,请在我的问题部分的顶部看到,print(objects)表示我拥有我的对象,基于此变量,您可以更新答案了吗

**打印(对象)**

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

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

2 个答案:

答案 0 :(得分:0)

您可以在{em>组合和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)));

答案 1 :(得分:0)

在这里,我使用forEach遍历数据以将所有常规学生数据收集到一个数组中,然后使用过滤器从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);