Intro
MongoDB Manual - Query Documents
Mongo Shell
The mongo Shell - MongoDB Manual
安裝
Mac
$ brew tap mongodb/brew
$ brew install mongodb-community-shell
(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
# Offset & Limit
> db.{colloection}.find().skip(20).limit(10)
> db.{colloection}.find({"key": "value"})
# Not - Inequality condition
> 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 (Field) 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": {} } });
Advanced Query
Not - Inequality condition
# Not empty string
> db.collection.find({ fieldName: { $ne: "" } })
# Field exists and is not null
> db.collection.find({ fieldName: { $ne: null, $exists: true } })
# Field exists and not empty array
> db.collection.find({ fieldName: { $ne: [], $exists: true } })
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