Skip to content

Instantly share code, notes, and snippets.

@tiagofrancafernandes
Last active September 21, 2022 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagofrancafernandes/0ce71d23b87db29c343d9687b9eafc14 to your computer and use it in GitHub Desktop.
Save tiagofrancafernandes/0ce71d23b87db29c343d9687b9eafc14 to your computer and use it in GitHub Desktop.
dev-mongodb-snippets

Last update at 2022-09-21 Tested on versions: 6.0|5.0

Query an Array

https://www.mongodb.com/docs/manual/tutorial/query-arrays/#query-an-array

db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
   { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
   { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
   { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
   { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);

Match find (were)

To specify conditions on the elements in the array field, use query operators in the query filter document: https://www.mongodb.com/docs/manual/reference/operator/query/#std-label-query-selectors https://www.mongodb.com/docs/manual/core/document/#std-label-document-query-filter

{ <array field>: { <operator1>: <value1>, ... } }
db.inventory.find( { tags: { $all: ["red", "blank"] } } )
// OR
db.inventory.find( { tags: "red" } )

// What is the difference?

Operators

// gt -> greater than
db.inventory.find( { dim_cm: { $gt: 25 } } )

// lt -> less than
db.inventory.find( { dim_cm: { $lt: 25 } } )

// eq -> equal
db.inventory.find( { dim_cm: { $eq: 25 } } )

// ne -> non equal
db.inventory.find( { dim_cm: { $ne: 25 } } )

Where

db.inventory.find( { $where: function() {
   return this.item == "paper"
} } );

In

db.inventory.find( { quantity: { $in: [ 5, 15 ] } }, { _id: 0 } )

// In using regex
db.inventory.find( { tags: { $in: [ /^be/, /^st/ ] } } )

Query for Ranges

db.bios.find( { birth: { $gt: new Date('1940-01-01'), $lt: new Date('1960-01-01') } } )

Result to Array

// Add .toArray() on end
db.getCollection('bios').find({}).toArray()
// or
db.bios.find({}).toArray()

Query for Multiple Conditions


Query Selectors

https://www.mongodb.com/docs/manual/reference/operator/query/#std-label-query-selectors

Comparison

For comparison of different BSON type values, see the specified BSON comparison order.

Name Description
$eq Matches values that are equal to a specified value.
$gt Matches values that are greater than a specified value.
$gte Matches values that are greater than or equal to a specified value.
$in Matches any of the values specified in an array.
$lt Matches values that are less than a specified value.
$lte Matches values that are less than or equal to a specified value.
$ne Matches all values that are not equal to a specified value.
$nin Matches none of the values specified in an array.

Logical

Name Description
$and Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.
$not Inverts the effect of a query expression and returns documents that do not match the query expression.
$nor Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
$or Joins query clauses with a logical OR returns all documents that match the conditions of either clause.

Element

Name Description
$exists Matches documents that have the specified field.
$type Selects documents if a field is of the specified type.

Evaluation

Name Description
$expr Allows use of aggregation expressions within the query language.
$jsonSchema Validate documents against the given JSON Schema.
$mod Performs a modulo operation on the value of a field and selects documents with a specified result.
$regex Selects documents where values match a specified regular expression.
$text Performs text search.
$where Matches documents that satisfy a JavaScript expression.

Geospatial

Name Description
$geoIntersects Selects geometries that intersect with a GeoJSON geometry. The 2dsphere index supports
$geoIntersects
.
$geoWithin Selects geometries within a bounding GeoJSON geometry. The 2dsphere and 2d indexes support
$geoWithin
.
$near Returns geospatial objects in proximity to a point. Requires a geospatial index. The 2dsphere and 2d indexes support
$near
.
$nearSphere Returns geospatial objects in proximity to a point on a sphere. Requires a geospatial index. The 2dsphere and 2d indexes support
$nearSphere
.

Array

Name Description
$all Matches arrays that contain all elements specified in the query.
$elemMatch Selects documents if element in the array field matches all the specified
$elemMatch
conditions.
$size Selects documents if the array field is a specified size.

Bitwise

Name Description
$bitsAllClear Matches numeric or binary values in which a set of bit positions all have a value of 0.
$bitsAllSet Matches numeric or binary values in which a set of bit positions all have a value of 1.
$bitsAnyClear Matches numeric or binary values in which any bit from a set of bit positions has a value of 0.
$bitsAnySet Matches numeric or binary values in which any bit from a set of bit positions has a value of 1.

Projection Operators

Name Description
$ Projects the first element in an array that matches the query condition.
$elemMatch Projects the first element in an array that matches the specified
$elemMatch
condition.
$meta Projects the document's score assigned during
$text
operation.
$slice Limits the number of elements projected from an array. Supports skip and limit slices.

Miscellaneous Operators

Name Description
$comment Adds a comment to a query predicate.
$rand Generates a random float between 0 and 1.
alias qq='mongo 172.17.0.1:1040/users --disableJavaScriptProtection --eval'
# qq 'db.getCollection("clientes").find( { $where: function() { return (this.name == "Tiago") } } );'
MongoDB shell version v3.4.4
connecting to: mongodb://172.17.0.1:1040/users
MongoDB server version: 3.4.4
{ "_id" : ObjectId("632a02d82258602135cb0b53"), "name" : "Tiago" }
alias qs='mongo 172.17.0.1:1040/users --quiet --disableJavaScriptProtection --shell'
qs <<'EOF'
> db.bios.find( { birth: { $gt: new Date('1940-01-01'), $lt: new Date('1960-01-01') } } )
> EOF

Result to array

alias qs='mongo 172.17.0.1:1040/users --quiet --disableJavaScriptProtection --shell'
qs <<'EOF'
> db.bios.find( { birth: { $gt: new Date('1940-01-01'), $lt: new Date('1960-01-01') } } ).toArray()
> EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment