The question is published on by Tutorial Guruji team.
How can I find the document that contains the a given JSON object?
Example:
suppose that in the database test
there is a document like this:
{ "identification": { "componentId": "3a4f6199-6141-4179-ac5f-f1bbcf627bb2", "componentType": "PivotTable", "dataDate": "2016-06-15T15:29:51.139+0200", "dataType": "PTF", "properties": { "contextId": "0329fe70-92f0-4b60-b3c2-79377adb8f95", "tags": ["tag1", "tag2"] } }, "viewData": { "lineGroups": [] } }
Now given only the identification
part of the document with partial keys set with value:
{ "componentType": "PivotTable", "properties": { "tags": ["tag1"] } }
Since the above document’s identification part is matching the given identification, then that document should be returned.
If I do db.test.find({identification: {/*the given identification segment*/}})
, mongodb will compare directly the identification part by checking exactly every entry in the document. In this case that document will not be returned.
Is there a way in mongodb query language that allows me to do this in relatively straight forward or easy way? Or I have to parse the entries in Identification object recursively in order to construct a query?
Answer
Mongo will try to match WHOLE properties subdocument, so in this case we will have to supply 1:1 document.
The way you could try to get this working is unwind every element and add it to query filter section.
{ "componentType": "PivotTable", "properties.tags": {$in:["tag1"]} }