Hope you folks can help, I’m doubting what I thought I had established,
and I can’t find much to assist in the documentation.
Am I correct in saying that using the default unique “_id” field as part of a compound query will make mongodb “short-circuit” the query operation in that any other fields as part of that request will simply act as a qualifier on that specific unique document as to whether it should be returned?
In other words, say I had a collection of simple documents, e.g.
with some of those fields being used for document ownership assertion.
Would an operation such as: findOneAndUpdate({_id: ..., $or:[{author_id: ...}, {share: ...}, {is_public: ...}]},{*doc*})
be an optimised way of querying/not fall back on collection scans?
That way someone who requests the doc with the wrong author_id or privileges will receive nothing, achieving the authentication objective.
The way i see it, if I’m including _id in the compound query, and the collection is indexed on the unique _id, wouldn’t any additional components to that request, i.e author_id, etc. have a negligible effect on query speed?
Hello @epic_pamek, welcome to the MongoDB Community forum!
Would an operation such as:
findOneAndUpdate(
{ _id: …, $or:[ {author_id: …}, {share: …}, {is_public: …} ] },
{doc}
)
be an optimised way of querying/not fall back on collection scans?
I see that the above query will use the default unique index on the _id field. You can generate a query plan using the db.collection.explain() and verify the index usage.
The way i see it, if I’m including _id in the compound query, and the collection is indexed on the unique _id, wouldn’t any additional components to that request, i.e author_id, etc. have a negligible effect on query speed?
Indexing will help the query access the data efficiently. You also have an option to define a compound index using more than one field, and the index can include the _id field.
Am I correct in saying that using the default unique “_id” field as part of a compound query will make mongodb “short-circuit” the query operation in that any other fields as part of that request will simply act as a qualifier on that specific unique document as to whether it should be returned?
Your query filter is an $and operation, and the matched document will be returned only when all the conditions are met.