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

4
  • This is a known bug, whereby MongoDB actually reads an array as an object. Commented Nov 12, 2012 at 8:46
  • Here is the JIRA for it: jira.mongodb.org/browse/SERVER-1475 Commented Nov 12, 2012 at 8: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?:) Commented Nov 12, 2012 at 8: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 Commented Nov 12, 2012 at 8:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.