[Mongo] Query & Mongo Shell 指南

Intro

MongoDB Manual - Query Documents


Mongo Shell

The mongo Shell - MongoDB Manual

安裝

Mac

$ brew tap mongodb/brew
$ brew install mongodb-community-shell

mongodb - Install mongo shell in mac - Stack Overflow

Compass. The GUI for MongoDB.

(TBC)


Basic of Shell

The mongo Shell - MongoDB Manual

$ mango "mongodb://..."

> show dbs

> use {database}

> show collections

> db.{collection}.find()

> db.{collection}.find().pretty()

Query Operations

MongoDB CRUD Operations

# Offset & Limit
> db.{colloection}.find().skip(20).limit(10)

> db.{colloection}.find({"key": "value"})

> db.{colloection}.find({"key": {$ne: "value"}})

# regular expressions (similar to SQL LIKE)
> db.{colloection}.find({key: /alu/})
> db.{colloection}.find({key: /ALU/i})

# Project (Select field)
db.{colloection}.find({}, {display_field:1, _id:0})

# Sorting (ASC vs DESC)
> db.{colloection}.find().sort(key: 1)
> db.{colloection}.find().sort(key: -1)

# Operater
> db.{colloection}.find({$and :[{conA}, {conB}]})

# Check if key exists
> db.{colloection}.find({ "search_key": { "$exists": true } });

# Check if value is not empty
> db.{colloection}.find({ "search_key": { "$gt": “” } });
> db.{colloection}.find({ "search_key": { "$gt": {} } });

$exists - MongoDB Manual


Advanced Query

Seach for all fields

db.mycollection.find({$where: function() {
    for (var key in this) {
        if (this[key] === "target_value") {
            return true;
        }
    }
    return false;
}});

Searching for value of any field in MongoDB without explicitly naming it

Geospatial Queries

near:

{
   : {
     $near: {
       $geometry: {
          type: "Point" ,
          coordinates: [  ,  ]
       },
       $maxDistance: ,
       $minDistance: 
     }
   }
}

Box矩陣方式可以參考:$box — MongoDB Manual

Leave a Reply

Your email address will not be published. Required fields are marked *