3

I'm trying to do something like this :

select * from table where not (a=3 and b=4 and c=3 or x=4)

I would expect this to work:

db.table.find({
  $not: {
    $or: [
      {
        $and: [
          { a: 3 },
          { b: 4 },
          { c: 3 }
        ]
      },
      { x: 4 }
    ]
  }
})

But it gives me an error:

 error: { "$err" : "invalid operator: $and", "code" : 10068 }

Is there another way to express it in mongodb?

0

2 Answers 2

5

Firstly, I don't think you mean "and" as a field will never 3 and 4 at the same time - it can only be 3 or 4. So, assuming you do want "documents where b is not 3 or 4, then you can use $nin (not in) like this:

db.table.find({b:{$nin: [3,4]}});
Sign up to request clarification or add additional context in comments.

1 Comment

Arh.. bad example. Lets say it a bit more complex. Just edited my post. This is my first post on stackoverflow, so i'm messing around :p
3

Using { $not : { $and : []} } will not work ($not is not like other operators, can only be applied to negate the check of other operators).

$and is not the problem here, this also doesn't work (though without reporting any errors):

{ $not : {  a : {$gt : 14} }  

you'd have to rewrite it to

{ a : {  $not : {$gt : 14} }

Coming back to your query:

`not (a=3 and b=4 and c=3 or x=4)` 

is equivalent to:

a!=3 and b!=4 and c!=3 or x!=4

and that you can do in mongo:

{a : { $ne : 3}, b : { $ne : 4} ...}

3 Comments

I think you should write the query completely because you're now leaving out the important $or clause (which is needed)
The reason i'm asking this, is because i'm trying to make a sql to mongodb converter. Not easy for me i must say. But I think I got a step closer with the "equivalent" example. It can be found here : klaus.dk/sqltomongodb
You're going to run into issues with trying to convert a relational query language to a document based on in a real hurry. Not worth the effort.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.