Reputation: 875
I have entry in a collection like this one:
{
"overlaps": [
{"BB1": "itemA", "iou": 0.1, "BB2": "itemB"},
{"BB1": "itemB", "iou": 0.45, "BB2": "itemC"}
],
"elemID": 1,
"otherfield2": "whateverelse"
}
I want to find entries that have element in the overlap array where overlaps.BB1:"itemA" and overlaps.BB2:"itemC". But for the same element in the overlaps array.
For instance, the example given here should not be retrieved, because I have overlaps.BB1:"itemA" and overlaps.BB2:"itemC", but not in the same element.
A valid element would be:
{
"overlaps": [
{"BB1": "itemA", "iou": 0.1, "BB2": "itemC"},
{"BB1": "itemB", "iou": 0.45, "BB2": "itemC"}
],
"elemID": 2,
"otherfield2": "whateverelse"
}
I have tried this but does not work
cursor = record1.find({"$and": [{"overlaps.BB1":"itemA"},{"overlaps.BB2":"itemC"}]})
How can I make this work? Or should I change my data structure in order to be able to perform such queries?
Thanks
Upvotes: 1
Views: 105
Reputation: 46491
You should use $elemMatch
to get the result
db.collection.find({
overlaps: {
$elemMatch: {
BB1: "itemA",
BB2: "itemC"
}
}
})
Upvotes: 1