1
db.foo.find();


_id    | type
-------------
10001     1
10002    'a'
10003    [1, 2, 3, 4]

As you know, the $type will match the type code in mongo query, like this:

db.foo.find({type: {$type: 4}});

_id | type

----------

10003, [1, 2, 3, 4]

and then, I write a javascript shell script called test.js

var curs = db.foo.find();
curs.forEach(showTypeCode);
function showTypeCode(cur) {
  print(cur.type + '-' + typeof(cur.type));
};

results:

1-number
a-string
1,2,3,4-object (this is an array, it's 4 in mongo)

here is my question, how can I get the array type code in the mongo shell

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sashimi
  • 793
  • 2
  • 8
  • 14
  • This is a known bug, whereby MongoDB actually reads an array as an object. – Sammaye Nov 12 '12 at 08:46
  • Here is the JIRA for it: https://jira.mongodb.org/browse/SERVER-1475 – Sammaye Nov 12 '12 at 08:52
  • @Sammaye,I should not use this demo,in javascript [] and {} are all object type.I want get the mongo data type 4.Is there any method for cur which can show this type code?:) – sashimi Nov 12 '12 at 08:56
  • I believe I read your question wrong originally, I have added a link to another question that should help, basically you have to test for a class of `array` – Sammaye Nov 12 '12 at 08:59

1 Answers1

1

Your first query of:

db.foo.find({type: {$type: 4}});

Will not actually work due to a bug. This is a known bug within MongoDB whereby it reads an array as an object when using the $type operator. You can vote and put your support to this JIRA: https://jira.mongodb.org/browse/SERVER-1475

As for solving the issue with the JS, this question might be of help to you: Detect if parameter passed is an array? Javascript

Arrays are Objects of the class Array so that is why you are getting object back. If you test for an instance of Array then it should work.

Community
  • 1
  • 1
Sammaye
  • 43,242
  • 7
  • 104
  • 146