okoboko
okoboko

Reputation: 4482

What's wrong with this MongoDB find() query (not equals)?

I'm trying to find all documents with a certain ID that don't have a status of -1.

Why does this give a syntax error in pymongo?

machine = db2.machine.find(
        {
            "account_id": account_id,
            "status": { $ne: -1 }
        }
   )

Note:

  1. account_id is a variable with the value ObjectId("5397929402b8541ae8a32349")
  2. If I remove the status line, it works fine.

Upvotes: 0

Views: 708

Answers (1)

Martin Konecny
Martin Konecny

Reputation: 59571

Unlike JavaScript, you need to wrap $ne into a string in Python.

So:

machine = db2.machine.find(
    {
        "account_id": account_id,
        "status": { "$ne": -1 }
    }
)

This is because in Python when you define a dictionary, you can't do

{key: "one"}

You need to do

{"key": "one"}

In the first case, "key" refers to a variable which doesn't exist. You could ammend the first case as follows:

>>> key = "name"
>>> {key: "one"}
{'name': 'one'}

An additional complication in your case was that you were trying to access a variable named $ne which is an invalid variable name.

Upvotes: 1

Related Questions