Note that there are some explanatory texts on larger screens.

plurals
  1. POMongo explicit/implicit AND behaving differently
    primarykey
    data
    text
    <p><strong>Basic question:</strong></p> <p>Are the following 2 queries meant to be equivalent?</p> <pre><code>(A) coll.find(k1:v1, k2:v2) // List of fields (B) coll.find($and: [{k1:v1}, {k2:v2}]) // $and the list of fields </code></pre> <p>If so, why do they show different behaviour? (see below). If not, how can I generate the former in C#?</p> <p><strong>Further discussion</strong></p> <p>I am indexing fields in a subdocument. Query (A) uses the indexes correctly but Query (B) does not.</p> <p>Here is some sample code (it will work directly in the mongo console):</p> <pre><code>{ _id : Guid ..other stuff.. Fields: { K1: V1, K2: V2 ...} } // Populate db.test.insert({_id:1,Fields:{K1:123,K2:456}}) db.test.insert({_id:2,Fields:{K1:456,K2:123}}) // Index on fields of subdocument db.test.ensureIndex({"Fields.K1": 1}) db.test.ensureIndex({"Fields.K2": 1})... // Execute some queries db.test.find({_id: {$lt: 20}, "$or": [{"Fields.K1": 123}, {"Fields.K2": 123}]}).explain() db.test.find({$and: [{_id: {$lt: 20}}, {"$or": [{"Fields.K1": 123}, {"Fields.K2": 123}]}]}).explain() </code></pre> <p>The first query uses the indexes as expected. The second does not.</p> <p><strong>Summary of questions</strong></p> <ol> <li>Are the two find() queries equivalent?</li> <li>If so, why is their behaviour different? If not, how are they different?</li> <li>How can I generate the find() without $and using the C# driver?</li> </ol> <p><strong>Edit</strong>--------</p> <p>For the record, the syntax I am using in C# is something along the lines of:</p> <pre><code>coll.find(Query.And([&lt;id query&gt;, &lt;fields query&gt;])); </code></pre> <p>Generating a QueryDocument manually does not work as it cannot contain multiple $or queries as $or is used as the key of a dictionary (and I need multiple $or in my actual query).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload