Mongodb query to find where the objects in the array do not match the elements of another field in the array

I have a set of documents like:

{
_id: ObjectId("55b164c65c1a8f360078c917"),
message_id: ["abc","def"],
message: [{message_id: "efgh", message_body: "somebody"}]
}

I want to find the mongodb request to find out the document whose message.message_id is missing from message_id. Can anyone help me with this.

+4
source share
1 answer

Probably the best approach with MongoDB 2.6 or more is using .aggregate()with $redact:

db.collection.aggregate([
    { "$redact": {
        "$cond": {
            "if": { 
                "$gt": [
                    { "$size": {
                        "$setIntersection": [
                            { "$map": {
                                "input": "$message",
                                 "as": "msg",
                                 "in": "$$msg.message_id"
                            }},
                            "$message_id" 
                        ]
                    }},
                    0
                ]
            },
            "then": "$$PRUNE",
            "else": "$$KEEP"
        }
    }}
])

" " , $map , "message_id" "messages" "message_id", $setIntersection. , "", , , "" . , $setIsSubset.

, $size , 0, . true "", "".

$where JavaScript- , :

db.collection.find({
    "$where": function() {
        var self = this;
        return self.message.map(function(el) {
            return el.message_id;
        }).filter(function(el) {
            return self.mesage_id.indexOf(el) != -1
        }).length == 0;
    }
})

, , , . pre MongoDB 2.6.

, "" . , $where , .

+2

Source: https://habr.com/ru/post/1629091/


All Articles