Filtering array in mongodb

Viewed 57

I want to query a document that looks like -:

{
    fname : "Michael",
    fields: [
                {
                    field:"[A,B,C,D]"
                },
                {
                    field:"[A,C,D]"
                }
            ]
}

Now from this document I want the resultant to be :

    {
            fname : "Michael",
            fields: [
                        {
                            field:"[A,C,D]"
                        }
                    ]

    } 

I am using this query to get the result, but I am getting error:-

db.mycollection.aggregate([
    {
        $project : {
            _id : 0,
            fields : { $filter : { input : "$fields", as : "f", cond : {"$$f.field" : {$nin : [/B/]}}}}}
        }
    }
])

Can anyone help in resolving the error ?

1 Answers

You can use $indexOfBytes to check the existence of a single character (returns -1 otherwise):

db.collection.aggregate([{
    $project : {
        _id : 0,
        fields : { 
            $filter : { 
                input : "$fields", 
                as : "f", 
                cond : { $eq: [ { "$indexOfBytes": [ "$$f.field", "B" ] }, -1 ] }
            }
        }
    }
}])

Mongo Playground

Related