Index of mixed types

87 views
Skip to first unread message

julman99

unread,
Nov 16, 2012, 5:32:00 PM11/16/12
to mongod...@googlegroups.com
Hello!

I have a simple question. I have a document with a field that can be an integer for some types of documents, and can be a string for other types. What I want is to store them as integers when they're integers to save space. 

The thing is that I need to index that field. Supose this

db.foo.ensureIndex({a:1})
db.foo.insert({a:1});
db.foo.insert({a:"2"});

In this case one of the documents stores "a" as integer and the other as string. How will the index behave in that case? Will it cast everything as a string? or will it keep separate btrees for each type?

Thanks a lot

Stephen Steneker

unread,
Nov 20, 2012, 7:36:50 AM11/20/12
to mongod...@googlegroups.com
Hi,

There will be one index, and the original types will be indexed (strings as string, etc).

That means that for your above examples, the following will return no results (searching for string as integer and vice-versa):
   db.foo.find({a:'1'})
   db.foo.find({a:2})

This also means you can insert two documents with similar keys but different types:
  db.foo.insert({a:1});
  db.foo.insert({a:'1'});

Similarly, strings and numbers have different sort orders so you may get unexpected sorting and ranged search results with mixed types.

The caveats may be fine for your use case, but in general I think it would be better to keep the type consistent rather than trying to save a few bytes.
 
Cheers,
Stephen

Reply all
Reply to author
Forward
0 new messages