如何在Nodejs上使用Mongo中的$ not运算符

时间:2017-06-25 16:07:19

标签: node.js mongodb

假设我有一个包含大量文档的mongo数据库:

{
    key: 'somekey',
    events: [
        {event_id: '001', event_info: 'blah'},
        {event_id: '001', event_info: 'blah'},
        ...etc
    ]
}

我想在文档的事件列表中添加一个新事件,其中key =' X'但仅当该事件(由event_id标识)尚未出现时才会出现。

我试过了:

collection.update({
        'key': newKeyValue,
        $not { events.event_id: newEventId }
    }, 
    {
        '$push': { 'events': newEvent }
    }, 
    {
        'upsert': true
    });

但我收到错误:" MongoError:未知的顶级操作员:$ not"。

我该如何做出这样的否定?

另请注意:我希望能够在一次原子操作中执行此操作。我知道我可以通过多个查询来完成它,但是如果我以后想要使用批量操作来设置它,那就无法工作。

1 个答案:

答案 0 :(得分:0)

您的查询错误请尝试以下查询

collection.update({
        'key': newKeyValue,
        events.event_id: { $not:{$eq: newEventId }}
    }, 
    {
        '$push': { 'events': newEvent }
    }, 
    {
        'upsert': true
    });

$ not用于查询上述字段

这可以解决您的问题

相关问题