Quick Tip: $size things up to $type

in Querying, Quick Tip

There are a number of quarky little MongoDB commands and queries hidden in the docs, two of them are $size and $type.

Does it really matter? $size that is …

The $size operator matches any array with the specified number of elements.

The basic use would be something like …

> db.ideas.find( { votes : { $size: 2 } } );

That would get you all the documents in the ideas collection that have exactly 2 items in the votes array (if say, you kept an array of votes.)

This however is of somewhat dubous use as:

You cannot use $size to find a range of sizes.

Meaning you can’t query for ideas that have 2 or more votes, or between 2 and 25 votes.

Are you her $type?

Another interesting query modifier is $type

The $type operator matches values based on their BSON type.

This might be useful to seek out documents that have a property that is an int and not a string; the types correspond numeric IDs (see the list below.)

To get documents with a property which has a value that is of the type of int the query might look something like this …

> db.mycollection.find( { foo : { $type : 16 } } );

Again, the practical usefulness of this might be rather thin, but who knows … it might come in handy someday!

MongoDB BSON Types

Type Name

Type Number

Double

1

String

2

Object

3

Array

4

Binary data

5

Object id

7

Boolean

8

Date

9

Null

10

Regular expression

11

JavaScript code

13

Symbol

14

JavaScript code with scope

15

32-bit integer

16

Timestamp

17

64-bit integer

18

Min key

255

Max key

127

0 Comments