Home > Net >  MongoDB select type object only
MongoDB select type object only

Time:10-22

I am trying to select documents using the $type operator.

Here is my collection :

{id: 1, a: [{b: "", c: ""}]},
{id: 2, a: {b: "", c: ""}}

Here is my queries :

db.collection.find( {a: { $type: "array"}} )
// It will return id: 1

db.collection.find( {a: { $type: "object"}} )
// It will return id: 2 AND id: 1

With the second query, I want to select only the object type.

https://mongoplayground.net/p/kp6UVzrUzjA
I am doing it wrong?

CodePudding user response:

Each type match with the type or with array that contains at least one member of that type. see this

Query

Test code here

db.collection.find({
  a: {
    $not: {
      $type: "array"
    },
    $type: "object"
  }
})

CodePudding user response:

You can also use an aggregation pipeline:

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

$type (aggregation)

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".

  • Related