node.js中的$ elemMatch投影

时间:2018-04-27 19:10:53

标签: node.js mongodb

dbo.collection("users")
            .findOne({email: emailGiven, "friends.email": element.email},
                     { friends: { $elemMatch: { email: element.email } } },
                     function(errT, resultT) {})

我在node.js中有上面的查询,但由于某种原因,查询的elemMatch部分不能在node.js上工作,但是当我在mongo终端中执行相同的查询时,它可以工作,所以我想也许是node.js不支持$ elemMatch?如果是这种情况,有人能告诉我node.js中这个查询的等价物吗?

我的数据库中的示例数据:

/* 4 */
{
    "_id" : ObjectId("5ad20cef8248544860ce3dc1"),
    "username" : "test",
    "email": "",
    "fullName" : "",
    "friends" : [{email: "",
                 status :""}],
    "alarms": [ {"id":111,
        "title": "TITLE",
        "location": "",
        "startTime": "10-10-1996 10:18:00",
        "endTime": "10-10-1996 10:18:00" }, {},{}

    ],
     "pnumber" : ""
}

2 个答案:

答案 0 :(得分:3)

node.js驱动程序findOne与MongoDB shell中的findOne具有不同的调用签名。您将字段选择对象作为projection参数的options元素传递:

dbo.collection("users")
    .findOne({"friends.email": email}, 
             {projection: { friends: { $elemMatch: { email: email } } } },
             function(errT, resultT) {...});

答案 1 :(得分:0)

如果您想find存储在某个变量中的任何值,请使用regex。您的查询应该看起来像

dbo.collection("users").findOne({
    email: new RegExp(emailGiven, 'i'),
    "friends.email": new RegExp(element.email, 'i')
}, {
    friends: {
        $elemMatch: {
            email: new RegExp(element.email, 'i')
        }
    }
}, function(errT, resultT) {})

i用于不区分大小写的比较

相关问题