Combining regular expressions and embedded objects in mongodb queries

I am trying to combine regular expression queries and inline objects and fail. I either click the restriction on mongodb, or just get something a little wrong, maybe some of them came across this. The documentation, of course, does not cover this case.

requested data:

{ "_id" : ObjectId("4f94fe633004c1ef4d892314"), "productname" : "lightbulb", "availability" : [ { "country" : "USA", "storeCode" : "abc-1234" }, { "country" : "USA", "storeCode" : "xzy-6784" }, { "country" : "USA", "storeCode" : "abc-3454" }, { "country" : "CANADA", "storeCode" : "abc-6845" } ] } 

Suppose a collection contains only one entry

This query returns 1:

 db.testCol.find({"availability":{"country" : "USA","storeCode":"xzy-6784"}}).count(); 

This query returns 1:

 db.testCol.find({"availability.storeCode":/.*/}).count(); 

But this query returns 0 :

 db.testCol.find({"availability":{"country" : "USA","storeCode":/.*/}}).count(); 

Does anyone understand why? This is mistake?

thanks

+4
source share
1 answer

You are referencing an inline storage file incorrectly - you are referencing it as an embedded object when you actually have an array . Compare these results:

 db.testCol.find({"availability.0.storeCode":/x/}); db.testCol.find({"availability.0.storeCode":/a/}); 

Using your doc example above, the first will not be returned, because the first storeCode does not have x in it ("abc-1234"), the second will return the document. This is good for the case when you look at a single element of an array and pass in position. To search all objects in an array, you want $ elemMatch

As an example, I added this second doc example:

 { "_id" : ObjectId("4f94fe633004c1ef4d892315"), "productname" : "hammer", "availability" : [ { "country" : "USA", "storeCode" : "abc-1234" }, ] } 

Now let's look at the results of these queries:

 PRIMARY> db.testCol.find({"availability" : {$elemMatch : {"storeCode":/a/}}}).count(); 2 PRIMARY> db.testCol.find({"availability" : {$elemMatch : {"storeCode":/x/}}}).count(); 1 
+2
source

Source: https://habr.com/ru/post/1414372/


All Articles