MongoDB - request for a nested field with an index

I am trying to figure out how I should structure the queries so that they fall into my index. I have documents structured like this:

{ "attributes" : { "make" : "Subaru", "color" : "Red" } } 

With index: db.stuff.ensureIndex({"attributes.make":1})

What I found is that the query for using dot notation gets into the index when querying with a document.

Example:

 db.stuff.find({"attributes.make":"Subaru"}).explain() { "cursor" : "BtreeCursor attributes.make_1", "nscanned" : 2, "nscannedObjects" : 2, "n" : 2, "millis" : 0, "nYields" : 0, "nChunkSkips" : 0, "isMultiKey" : false, "indexOnly" : false, "indexBounds" : { "attributes.make" : [ [ "Subaru", "Subaru" ] ] } } 

against

 db.stuff.find({attributes:{make:"Subaru"}}).explain() { "cursor" : "BasicCursor", "nscanned" : 2, "nscannedObjects" : 2, "n" : 0, "millis" : 1, "nYields" : 0, "nChunkSkips" : 0, "isMultiKey" : false, "indexOnly" : false, "indexBounds" : { } } 

Is there a way to get a document style query on an index? The reason is that when building queries from my permanent objects, it’s much easier to serialize them as documents, rather than something using dot notation.

I will also add that we use a home-built data display layer created using Jackson. Does something like Morphia use help in building these queries correctly?

+6
source share
1 answer

Did you do any more digging and this thread explains what happens with the subdocument request. My problem was that in order to make a query based on a subdock, like dotted notation, I needed to use elemMatch.

 db.stuff.find({"attributes":{"$elemMatch" : {"make":"Subaru"}}}).explain() { "cursor" : "BtreeCursor attributes.make_1", "nscanned" : 2, "nscannedObjects" : 2, "n" : 0, "millis" : 2, "nYields" : 0, "nChunkSkips" : 0, "isMultiKey" : false, "indexOnly" : false, "indexBounds" : { "attributes.make" : [ [ "Subaru", "Subaru" ] ] } } 
+7
source

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


All Articles