[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"})

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

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

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

$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:

{
   <location field>: {
     $near: {
       $geometry: {
          type: "Point" ,
          coordinates: [ <longitude> , <latitude> ]
       },
       $maxDistance: <distance in meters>,
       $minDistance: <distance in meters>
     }
   }
}

Leave a Reply

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