taffies
taffies

Reputation: 11

Can mango syntax take in two $OR operators in one query?

I have problems putting two $OR operations in one query statement. It ignores the earlier $OR operators and only takes into consideration the last $OR operator in the query. (There is no issue when only one $OR operator is in the query.) Am wondering if I am doing something wrong, if this is possible to achieve using CouchDB, or if there is a way around it. Thank you!

I am running a blockchain on Hyperledger Fabric using CouchDB as the state database. (https://hyperledger-fabric.readthedocs.io/en/release-1.4/couchdb_tutorial.html) I am definitely not seasoned in the workings of CouchDB so I may be slightly ignorant in how it's supposed to behave.

It's sort of complicated but my objects basically "belong" to two owners and companies. I want to perform queries such that when I search for a owner or a company, it searches in two different columns to see the the owner/company exists.

e.g. When I search for Company A, it should search for Company A in both company1_id and company2_id.

Query Statement:

{"selector":{"docType":"object", "owner_id": {"$in": ["owner_id"]}, "$or": [{"company1_id": { "$in": ["company_id_1", "company_id_2"]}}, {"company2_id": { "$in": ["company_id_1", "company_id_2"]}}], "$or": [{"owner1_id": { "$in": ["owner_id_1", "owner_id_2"]}}, {"owner2_id": { "$in": ["owner_id_1", "owner_id_2"]}}], "object_id":{"$lt":"99999999999"}}, "sort": [{"object_id": "desc"}]}

Expected: Get results that corresponds to the above query

What happened: I get results which ignored the first query, so it returns results which corresponds to the following query:

{"selector":{"docType":"object", "owner_id": {"$in": ["owner_id"]}, "$or": [{"owner1_id": { "$in": ["owner_id_1", "owner_id_2"]}}, {"owner2_id": { "$in": ["owner_id_1", "owner_id_2"]}}], "object_id":{"$lt":"99999999999"}}, "sort": [{"object_id": "desc"}]}

Upvotes: 1

Views: 752

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79614

Yes, it ignores it because it's a standard JSON object, so each key must be unique. You have the same situation with a simpler example:

{
    "foo": 123,
    "foo": 345,
}

Depending on whether your JSON parser accepts the first or last value, your resulting object will be either { "foo": 123 } or { "foo": 345 }.

The solution is to use another logical layer. In your case, you probably want an $and wrapping your $or conditions:

"$and": [
    { "$or": [ ... ] },
    { "$or": [ ... ] },
]

Upvotes: 1

Related Questions