Rail Suleymanov
Rail Suleymanov

Reputation: 359

Multiple query in pymongo

I have mongoDB with items of following structure:

{
    "some_field": {
        "date": 123,
        "text": "secondary text"
    },
    "text": "primary text"
}

I want to write queries in pymongo that check for text field of top level and apply conditional query at the "date" field of second level. I'm getting filters of the form:

filter = {
    "text": "some target text",
    "date": {
        "start": some_int_val1,
        "end": some_int_val2
    }
}

I can create query to "text" without any problem:

query = dict()
query["text"] = filter["text"]

But I'm stucked about how to construct an $and query on "some_field.date". I tried to simply combine them in one query:

query["somefield.date"] = [{"$gte": filter["common_date"]["start"]}, {"$lte": filter["common_date"]["end"]}]

But it didn't work. Also, I tried what I thought would work, but it throws an error:

query["somefield.date"] = { $and: [{"$gte": filter["date"]["start"]}, {: filter["date"]["end"]}]}

Saying "statement expected, found Py:AND_KEYWORD". How can I overcome this?

Upvotes: 1

Views: 3035

Answers (2)

chridam
chridam

Reputation: 103445

In JavaScript, you can create the query object using the bracket-notation like this:

var filter = {
    "text": "some target text",
    "date": {
        "start": 100,
        "end": 150
    }
};

var query = { "some_field": { "date": {} } };
query["text"] = filter["text"];
query["some_field"]["date"]["$gte"] = filter["date"]["start"];
query["some_field"]["date"]["$lte"] = filter["date"]["end"];
console.log(JSON.stringify(query)); // {"some_field":{"date":{"$gte":100,"$lte":150}},"text":"some target text"} 

Use the same concept in python to create your query dictionary as follows:

>>> filter = {
...     "text": "some target text",
...     "date": {
...         "start": 100,
...         "end": 150
...     }
... }
>>>
>>> print(filter)
{'date': {'start': 100, 'end': 150}, 'text': 'some target text'}
>>> query = { "some_field": { "date": {} } }
>>> query["text"] = filter["text"]
>>> query["some_field"]["date"]["$gte"] = filter["date"]["start"]
>>> query["some_field"]["date"]["$lte"] = filter["date"]["end"]
>>> print(query)
{'text': 'some target text', 'some_field': {'date': {'$lte': 150, '$gte': 100}}}
>>>

Upvotes: 0

thegreenogre
thegreenogre

Reputation: 1579

This should work

query["somefield.date"] = {"$gte": filter["date"]["start"],"$lte": filter["date"]["end"]}

Your final query should look like :

{
    'somefield.date': {'$gte': some_int_val1, '$lte': some_int_val2}, 
    'text': 'some target text'}
}

Upvotes: 1

Related Questions