I want to query the collection with a structure like such that [1,1,1] would return the above object, because it contains every thing in the query. However if the query was [1,1,1,1], I want it to reject, because there’s too many ones.
Does this query make sense? How would I accomplish this in mongo?
You want to return all documents in a Mongo collection that have exactly three 1’s in their items array? that’s how i understood the question, but i may be wrong.
I’m terrible at explaining myself. Let me be less vague.
I have this data structure.
{
name: "Whatever",
steps: [
{ time: 0, name: "A" },
{ time: 241, name: "B" },
{time: 250, name: "B" }, // and so on
]
}
I want to search this collection with a given time and set of names, and get models that have steps before the given time, for all of the given names, but no more.
For example, querying time: 300, names:[“A”, “B”]` would return the model above, because it has A and B before 300.
However if I queried time: 300, names:[“A”, “A”, “B”]`, it wouldn’t because it doesn’t have 2 “A” before 300.
Usually, if you want to match two properties in an embedded document array, you need to use $elemMatch, that doesn’t quite cover the requirement to have exactly two documents with the same name before a time though.
You might need to use $where, and pass a stringified javascript function to mongo to execute.
Which will run for each document, checking that there are exactly two steps before 300 with the name “A” and exactly one step before 300 with the name “B”
I already wrote a function after the fact to do what I want, but if there’s a benefit here, I’ll move it into the query. I see it runs per-element in the array. Is there way to initialize a variable outside of that function to use as state tracking?