Reputation: 126694
If I had a field in every document of a collection called array_field
, which consists of elements of type object
, could I query for a specific field in the objects?
- collection
- document1
- array_field
0: { type: tree, age: 143 }
1: { type: sunflower, age: 1 }
2: { type: fungus, age: 3 }
- document2
- array_field
0: { type: plane, age: 38 }
1: { type: plant, age: 2 }
2: { type: fungus, age: 1 }
Is there a possibility to query for every document that has an object in its array_field
with type fungus
?
If that is not possible, is there a way to query for documents by specifying an exact object
?
I do not know how I would go about writing the query: .where('array_field', 'array_contains', /*how do I define this object*/)
. Would it just be a JSON object like this: {type: fungus, age: 2}
?
The query I am aiming to achieve is the following:
where('array_field', 'array_contains', 'type:fungus')
Which would return document1
and document2
, but I could not find any hints on syntax for a case like this.
Upvotes: 0
Views: 99
Reputation: 317467
This isn't possible with the current structure of your data. array_contains only works when matching the entire contents of an array element, not just specific object fields.
Instead, you could restructure you data to use an object with unique types, and a boolean value, so that you could query for something like types.fungus == true
:
document
types {
fungus: true
plant: true
}
It is common to duplicate data in nosql database to suit the specific queries you need to perform.
Upvotes: 2