Don't get bitten by mungos

... or Mongos

Order of properties matters in objects

!=
{  "city": "SF",  "state": "CA"}
{  "state": "CA",  "city": "SF"}

Object queries
find({address: { city:"SF", state:"CA" }}) - badfind({ 'address.city': "SF", 'address.state': "CA" }) - better

Sort specifiers

 find().sort({ name: 1, _id: 1 })               !==  find().sort({ _id: 1, name: 1 })


Collection indexes

 collection.ensureIndex({ name: 1, address: 1 })                      !==                    collection.ensureIndex({ address: 1, name: 1 })

Sort on an array field


db.places:
{
  _id: "A",
  ratings: [5, 1, 3]
},
{
  _id: "B",
  ratings: [2, 4, 9]
},
{
  _id: "C",
  ratings: [1]
} 

Mongo sorting


find().sort({ locations: 1 })

find({ locations: { $gt: 1 } }).sort({ locations: 1 })
locations:     x x 2 3 4 5 9

_id:    
A C B A B A B
_id:     A C B A B A B
locations:     1 1 2 3 4 5 9

$near sorting


db.restaurants

{  _id: "A",  locations: [ [1, 2], [1, 0] ]},
{ _id: "B", locations: [ [ 0, 0 ] ]}

null, undefined






Original blog post:


devblog.me/wtf-mongo

Don't get bitten by mungos (or mongos)

By Slava Kim

Don't get bitten by mungos (or mongos)

  • 1,681