Čamo
Čamo

Reputation: 4172

Mongodb how to get $type "object"

Can somebody tell me please how to get items which field is $type object? The problem is that Mongodb includes $type array (which contains objects) to result. But I dont want arrays but objects.

{fieldName: {$type: 3}}

returns items like:

{
    _id: xxxx,
    fieldName: [
        {a: 'aaa'}, 
        {b: 'bbb'}
    ]
}

Upvotes: 1

Views: 985

Answers (1)

mickl
mickl

Reputation: 49975

You can use Aggregation Framework's $type operator:

db.collection.aggregate([
    {
        $match: {
            $expr: {
                $eq: [ { $type: "$fieldName" }, "object" ]
            }
        }
    }
])

Unlike the $type query operator, which matches array elements based on their BSON type, the $type aggregation operator does not examine array elements. Instead, when passed an array as its argument, the $type aggregation operator returns the type of the argument, i.e. "array".

MongoDB Playground

Upvotes: 2

Related Questions