0

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?

2
  • Can you elaborate by explaining the actual business need? if it's to validate input coming from a single source then it should be done on insert/update else can you just save the baz field as a root level field? Commented Feb 28, 2021 at 16:14
  • I need to check all the documents in the collection to have same baz for each document. Maybe I can get all the _id for the documents with different baz. Commented Mar 1, 2021 at 0:38

1 Answer 1

1

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 }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.