【问题标题】:How to find if element exists in document - MongoDB?如何查找文档中是否存在元素 - MongoDB?
【发布时间】:2017-06-29 12:13:06
【问题描述】:

我正在尝试检查我的集合以返回文档中数组元素为特定值的所有文档。

例如,这是我的 JSON 文档之一:

[
{
    "employer" : "employer1@gmail.com",
    "applicants" : [
        {
            "email" : "joe@gmail.com"
        },
        {
            "email" : "fred@gmail.com"
        }
    ]
},
{
    "employer" : "employer2@gmail.com",
    "applicants" : [
        {
            "email" : "steven@gmail.com"
        }
    ]
},
{
    "employer" : "employer3@gmail.com",
}
]

现在,我想要返回的是申请者数组不包含电子邮件"steven@gmail.com" 或存在no applicants array 的任何文档。

在我上面的 JSON 示例中,它应该返回 employer1employer2 的文档。

我已经将申请人steven@gmail.com does not exist,所以雇主1,但我不明白我如何也包括employer3。我该怎么做?

这是我目前在 JavaScript 中的查询:

collection.find({"applicants.email" : {$ne : req.user.username}}, {}, function(e,docs){
            res.json(docs);
            console.log(docs);
    });

【问题讨论】:

  • 使用 $elemMatch 在这样的数组中查找对象{ applicants:{ $elemMatch: { email :{ $ne:req.user.email }}}}
  • 这似乎不起作用,它返回 []。如果我将 "applicants" : [] 添加到我的文档中,我的原始查询可以工作,但我认为我不应该添加一个空白数组来让这个工作正常吗?
  • 嗯,很奇怪,我现在无法测试。然后尝试像 { $or: [{"applicants: $or: [{ $exists: false}, {$size: 0}] ,{"applicants.email" : {$ne : req.user.username}]} 这样的原始查询,这应该返回申请者数组不存在或为空或电子邮件不是 req.user.username 的文档

标签: javascript node.js mongodb nosql


【解决方案1】:

试试下面的查询,可能对你有帮助:-

有关如何使用它的更多信息,请参阅$size

如果applicants.email 不等于req.user.usernameapplicants 数组大小为0,则此查询将返回结果。

collection.find({$or:[
                     {"applicants.email" : {$ne : req.user.username}},
                     {applicants: {$size: 0}}
                 }], function(e,docs){
        console.log(docs);
});

我从未尝试过查询。让我知道它是否给出任何错误。

你也可以试试这个:-

如果applicants.email 不等于req.user.usernameapplicants 数组不存在,则此查询将返回结果。

 collection.find({$or:[
                     {"applicants.email" : {$ne : req.user.username}},
                     {applicants: {$exists: false}}
                 }], function(e,docs){
        console.log(docs);
});

更多信息请参考$exists

希望它会有所帮助。

【讨论】:

  • 谢谢!我想出了您发布的第二个选项,并且有效!
  • 很高兴为您效劳!!如果有帮助,您可以投票给答案吗? :)
【解决方案2】:

试试这个:

collection.find({applicants: {$not: {$size: 0}}},function(err,data){
    if(err){
        console.log(err);
    }
    else{
        console.log("Applicats Array Where size is not zero:");
        console.log(data);
    }
});

【讨论】:

    【解决方案3】:

    试试这个查询,$nin 对这种情况很有用

    collection.find({"applicants.email" : {$nin:["steven@gmail.com"]}}, {}, function(e,docs){
                res.json(docs);
                console.log(docs);
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多