Unfortunately, MongoDB does not support any method for querying all fields with a specific value. There is an existing Jira ticket requesting this improvement: https://jira.mongodb.org/browse/SERVER-1248 . Feel free to comment, vote or follow this ticket.
Meanwhile, the usual way to handle this is to change the MongoDB schema. For your example, you modify the existing schema:
{"123": "apple", "217": "pear", "179": "orange"} {"831": "pear", "189": "grapes"}
And you can create it something like this:
{ tags: [ { cid: "123", value: "apple" }, { cid: "217", value: "pear" }, { cid: "179", value: "orange" }, ] } { tags: [ { cid: "831", value: "pear" }, { cid: "189", value: "grapes" }, ] }
Once you do this, you can run the follwing query to find all the documents you need:
db.docs.find( {'tags.value': "apple" } )
Note that this schema allows you to index the tags.cid and tags.value fields that are not in the original schema.
Hope this helps.
-William
source share