1

Say I have a mongo db with a bunch of documents like this:

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

I want to add a new event to the event list of the document where key='X' but only if that event (identified by event_id) is not already present.

I tried this:

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

But I get the error: "MongoError: unknown top level operator: $not".

How can I do a negation like this?

Note also: I would like to be able to do this in one atomic operation. I know I could do it with multiple queries, but if I later want to set this up using bulk operations, that won't work.

  • You actually want `$ne` here for this case. Also, never use negations on matches in combination with "upsert". You likely should be doing two operations instead. [See Model a "likes" voting system with MongoDB](https://stackoverflow.com/questions/28006521/how-to-model-a-likes-voting-system-with-mongodb) – Neil Lunn Jun 25 '17 at 22:22

1 Answers1

0

your query is wrong try below query

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

$not is use to query the field as above

may this solve your issue

Ratan Uday Kumar
  • 5,738
  • 6
  • 35
  • 54