[SERVER-14010] Use of $where within $elemMatch Created: 21/May/14  Updated: 04/Aug/17  Resolved: 21/May/14

Status: Closed
Project: Core Server
Component/s: JavaScript, Querying
Affects Version/s: 2.4.9, 2.4.10, 2.6.0, 2.6.1
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Neil Lunn Assignee: David Storch
Resolution: Duplicate Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
duplicates SERVER-12439 $where in $elemMatch no longer valid ... Closed
duplicates SERVER-13503 The $where operator should not be all... Closed
Related
is related to DOCS-3449 Doc that $where must be top-level Closed
Operating System: ALL
Steps To Reproduce:

Set up a document with a sub-document in an array:

    db.docs.insert({
        "data": [{ "name": "Kimberly" }]
    })

Attempt a JavaScript match as done by the poster:

    db.docs.find({
        "data": {
            "$elemMatch":{
                 "$where" : "this.name.toLowerCase().indexOf('kim') ==0"
            }
        }
    });

Produces the error in 2.6:

error: {
        "$err" : "Can't canonicalize query: BadValue $elemMatch cannot contain $where expression",
        "code" : 17287
}

Which clearly seems intentional, but in prior versions the query produces a matching result without throwing the error.

Participants:

 Description   

Different behavior of $where within $elemMatch from 2.4 version to 2.6 the issue was raised in this question

It is noted to the poster that they should not be using the type of query as shown as the results can be achieved by other means.

This probably requires a documentation patch to cover the changed behavior.



 Comments   
Comment by Rodolphe [X] [ 04/Aug/17 ]

I need to ask, what is the rationale behind this constraint ? For some reason, I have to write queries in plain JSON so using $where inside $elemMatch was very pratictal and without this, the queries I'm trying to write are just a pain. And as I read it on https://docs.mongodb.com/manual/core/server-side-javascript/, I can't inject javascript in mongoDb queries apart from top-level `$where`s or MapReduce.

Comment by David Storch [ 21/May/14 ]

2.6 enforces that $where appears at the top level of the query document. The allowance of $where below $elemMatch in 2.4 was determined to be unintentional. Resolving as a duplicate of SERVER-13503 and SERVER-12439. See the "Issue Status" box in SERVER-13503 for more detail.

I have opened DOCS-3449 in order to explicitly document that $where has to be at the root level of the query document.

Generated at Thu Feb 08 03:33:34 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.