Question

Suppose I have several documents like so

{
  title: 'blah',
  value: {
    "A": {property: "foo"},
    "B": {property: "bar"},
    "C": {property: "foo"},
    "D": {property: "foo"}
  }
}

{
  title: 'blah2',
  value: {
    "A": {property: "bar"},
    "B": {property: "bar"},
    "C": {property: "bar"},
    "D": {property: "foo"}
  }
}

What mongodb query will get me all of the documents / hash keys that have {property: "foo"}

(I know this can be done using js after the query, but can it be done within the query itself?)

Was it helpful?

Solution

The trouble is that there's no wildcard for object keys (see https://jira.mongodb.org/browse/SERVER-267), so you wouldn't be able to do this without listing all of the keys in your "value". That might be an option if you know what all of the keys are, but I imagine you don't.

If you converted "value" to an array rather than an object, you could do a query easily (which would return the documents, not the hash keys).

OTHER TIPS

As the first answer says, there is nothing in the mongodb query language that would allow you to do this type of query.

You might want to consider altering your schema to make value an array like this:

value: [
         { name : "A", property : "bar" },
         { name : "B", property : "bar" },
         { name : "C", property : "bar" },
         { name : "D", property : "foo" }
       ]

Then you could index on value.property and run a query on value.property = "foo".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top