Reputation: 217
I need to verify that for each document it has the same value for the baz field.
The structure looks like this.
{
_id : 111111,
foo : 123123,
bar : [
{
subId : 121212,
baz : abc123
},
{
subId : 131313,
baz : abc123
},
]
},
{
_id : 222222,
foo : 234234,
bar : [
{
subId : 212121,
baz : def456
},
{
subId : 313131,
baz : def456
},
]
},
Basically I just need to make sure that for each document, baz should be always the same. How can I query it?
Upvotes: 0
Views: 37
Reputation: 4452
Try This:
db.allSame.aggregate([
{
$addFields: {
"uniqueBazCount": {
$sum: {
$map: {
input: "$bar",
as: "item",
in: {
$cond: [{ $eq: ["$$item.baz", { $arrayElemAt: ["$bar.baz", 0] }] }, 0, 1]
}
}
}
}
}
},
{
$match: { uniqueBazCount: 0 }
}
]);
To get the docs with different values change $match
as below:
{
$match: {
uniqueBazCount: { $gt: 0 }
}
}
Upvotes: 1