---
# System prepended metadata

title: MongoDB Basic Cluster Administration
tags: [mongodb]

---

# MongoDB Basic Cluster Administration

* Install Mongodb compass
* MongoDB Community Server
    * Mongodb shell & vim $PATH 
            $     vim ~/.bash_profile 
            $     source ~/.bash_profile
            $     echo $PATH
 1. $ mongo --nodb #Prevents the shell from connecting to any database instances.
 2. $ mongod
     * exception in initAndListen: 29 Data directory /data/db not found., terminating
         * $ sudo mkdir -p /data/db 
     * exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating
         * $ sudo chown -Rv Renny /data/db
     * $ mongod
         * waiting for connections on port 27017
         * $ mongo
         * http://127.0.0.1:27017/
             * It looks like you are trying to access MongoDB over HTTP on the native driver port.

To load and start the MongoDB background service, open Terminal and execute the following commands :+1: 
3. Hombrew services
> $ brew tap homebrew/services
> $ brew services start mongodb
> $ brew services list
> $ mongod --version
> $ brew services stop mongodb

* Stop mongod Processes
> From the Linux command line, shut down the mongod using the --shutdown option in the following command:

    Use CTRL-C
    $ mongod --shutdown
    $ kill <mongod process ID>

___

* setup MongoDB Atlas free 
    * connet 
        * mongo "mongodb+srv://renny-cluster0-vbwkh.gcp.mongodb.net/test" --username renny

* load data
      > load("loadReviewsDataset.js")

### CRUD
- insertOne()
- insertMany()
```js=
db.movieScratch.insertMany(
    [
        {
  	    "_id" : "tt0084726",
  	    "title" : "Star Trek II: The Wrath of Khan",
  	    "year" : 1982,
  	    "type" : "movie"
          },
          {
  	    "_id" : "tt0796366",
  	    "title" : "Star Trek",
  	    "year" : 2009,
  	    "type" : "movie"
          },
          {
  	    "_id" : "tt0084726",
  	    "title" : "Star Trek II: The Wrath of Khan",
  	    "year" : 1982,
  	    "type" : "movie"
          },
          {
  	    "_id" : "tt1408101",
  	    "title" : "Star Trek Into Darkness",
  	    "year" : 2013,
  	    "type" : "movie"
          },
          {
  	    "_id" : "tt0117731",
  	    "title" : "Star Trek: First Contact",
  	    "year" : 1996,
  	    "type" : "movie"
        }
    ]
    {
    	ordered: false
    }
);

```
- Update Operators
> For update operations, update operators specify how to modify specific fields in documents matching a filter. Fields may be added, deleted, or have their value changed in some way. Update operators define what modifications to make with respect to one or more fields in matching documents.
- updateOne() 
    >https://docs.mongodb.com/manual/reference/operator/update/
    
$set | $unset
> The $set operator replaces the value of a field with the specified value. If the field does not exist, $set will add a new field with the specified value.If you specify multiple field-value pairs, $set will update or create each field.
```js=
db.movieDetails.updateOne({
	title:"The Martian"
}, {
	$set:{
		"awards":{
		"wins": 8,
		"nominations": 14,
		"text":"test for5"
		}
	}
})
```
$inc
> ++
```js=
db.movieDetails.updateOne({
	title:"The Martian"
}, {
	$inc: {
		"tomato.reviews": 3,
		"tomato.userReviews": 4
	}
})
```
$push | $each
> add datas
```js=
let reviewText1 = [
	"The Martian...."
].join()
let reviewText2 = [
	"22The Martian...."
].join()
db.movieDetails.updateOne({
	title:"The Martian"
}, {
	$push: {
		reviews: {
			$each: [{
				rating:4.5,
				reviewer:"suencer H.",
				text:reviewText1
			},{
				rating:8.5,
				reviewer:"suencer H.",
				text:reviewText2
			}
			]
		}
	}
})
```
- updateMany()
    >https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/#db.collection.updateMany

$unset
```js=
db.movieDetails.updateMany({
	rated: null
}, {
	$unset: {
		rated: ""
	}
})
```

- replaceOne()
  >Important aspect to consider about replaceOne:The replacement document cannot contain update operators.
replaceOne will apply changes to only one document, the first found in the server that matches the filter expression, using the $natural order of documents in the collection. 
    >https://docs.mongodb.com/manual/reference/method/db.collection.replaceOne/
    
```js=
let filter = {title: "House, M.D., Season Four: New Beginnings"}

let doc = db.movieDetails.findOne(filter);

doc.poster;

doc.poster = "https://www.imdb.com/title/tt1329164/mediaviewer/rm2619416576";

doc.genres;

doc.genres.push("TV Series");

db.movieDetails.replaceOne(filter, doc);
 ```
 
- deleteOne()
- deleteMany()
```js=
db.reviews.deleteOne({
	_id: ObjectId("5cfddf4dd20a907fe99bc99a")
})

db.reviews.deleteMany({
	reviewer_id: 759723314
})
```
### Query Operators
 > https://docs.mongodb.com/manual/reference/operator/query

$eq	
> Matches values that are equal to a specified value.
```js=
db.movieDetails.find({runtime:{$eq:90}}).count()
```

$ne
> Matches all values that are not equal to a specified value.
```js=
db.movieDetails.find({rated: {$ne: "UNRATED"}},{_id: 0, title: 1, rated: 1})
```


$gt 
> Matches values that are greater than a specified value.
```js=
db.movieDetails.find({runtime:{$gt:90}})

db.movieDetails.find({runtime:{$gt:90}}, {_id: 0, title: 1, runtime: 1})
```
$lt
> Matches values that are less than a specified value.
```js=
db.movieDetails.find({runtime:{$gt:90, $lt: 120}}, {_id: 0, title: 1, runtime: 1})
```

$gte | $lte
> Matches values that are greater than or equal to a specified value.
> Matches values that are less than or equal to a specified value.
```js=
db.movieDetails.find({runtime:{$gte:90, $lte: 120}}, {_id: 0, title: 1, runtime: 1})

db.movieDetails.find({runtime:{$gte:180}, "tomato.meter": {$gte: 95}}, {_id: 0, title: 1, runtime: 1, "tomato.meter": 1})
```

$in
> **Matches any of the values specified in an array.**
```js=
db.movieDetails.find({rated: {$in: ["G", "PG"]}},{_id: 0, title: 1, rated: 1})
```
$nin
> **Matches none of the values specified in an array.**
```js=
db.movieDetails.find({rated: {$nin: ["G", "PG"]}},{_id: 0, title: 1, rated: 1})
```

Problem:

Using the $in operator, filter the video.movieDetails collection to determine how many movies list "Ethan Coen" or "Joel Coen" among their writers. Your filter should match all movies that list one of the Coen brothers as writers regardless of how many other writers are also listed. Select the number of movies matching this filter from the choices below.

```js=
db.movieDetails.find({writers: {$in: ["Ethan Coen", "Joel Coen"]}},{_id: 0, title: 1, rated: 1}).count()
```

### Element Operators
>https://docs.mongodb.com/manual/reference/operator/query/type/

$exists
> When <boolean> is true, $exists matches the documents that contain the field, including documents where the field value is null. If <boolean> is false, the query returns only the documents that do not contain the field.
```js=
db.movies.find({mpaaRating: {$exists: true}})
db.movies.find({mpaaRating: {$exists: false}})
```

$type
> $type selects the documents where the value of the field is an instance of the specified BSON type(s). Querying by data type is useful when dealing with highly unstructured data where data types are not predictable.
```js=
db.movies.find({viewerRating: {$type: "int"}})
db.movies.find({viewerRating: {$type: "double"}})
```

Problem:

Connect to our class Atlas cluster from the mongo shell or Compass and answer the following question. How many documents in the 100YWeatherSmall.data collection do NOT contain the key atmosphericPressureChange.

> use 100YWeatherSmall

```js=
 db.data.find({atmosphericPressureChange: {$exists:false}}).count()
```

### Logical Operators
> https://docs.mongodb.com/manual/reference/operator/query-logical/

$and 
> on the same filds
```js=
db.movieDetails.find({$and: [
{"metacritic":{$ne: null}},
{"metacritic": {$exists: true}}]},
{_id: 0, title: 1, "metacritic": 1})

'''$ne not equal to a specified value.'''

db.movieDetails.find({$and: [
{"metacritic": null},
{"metacritic": {$exists: true}}]},
{_id: 0, title: 1, "metacritic": 1})
```

Problem:

Connect to our class Atlas cluster from the mongo shell or Compass and view the ships.shipwrecks collection. In this collection, watlev describes the water level at the shipwreck site and depth describes how far below sea level the ship rests. How many documents in the ships.shipwrecks collection match either of the following criteria: watlev equal to "always dry" or depth equal to 0.

```js=
db.shipwrecks.find({$or: [
{"watlev":{$eq: "always dry"}},
{"depth": {$eq: 0}}]}).count()
```

### Array Operators
> https://docs.mongodb.com/manual/reference/operator/query-array/

$all 
> The $all operator selects the documents where the value of a field is an array that contains all the specified elements. To specify an $all expression, use the following prototype:

```js=
db.movieDetails.find({genres: {$all: ["Comedy", "Crime", "Drama"]}},
{_id: 0, title: 1, genres: 1}).pretty()
```
Problem:

Connect to our class Atlas cluster from the mongo shell or Compass and view the 100YWeatherSmall.data collection. The sections field in this collection identifies supplementary readings available in a given document by a three-character code. How many documents list: "AG1", "MD1", and "OA1" among the codes in their sections array. Your count should include all documents that include these three codes regardless of what other codes are also listed.
> use 100YWeatherSmall

```js=
db.data.find({sections: {$all: ["AG1", "MD1", "OA1"]}},
{_id: 0, title: 1, sections: 1}).count()
```

$size
> The $size operator matches any array with the number of elements specified by the argument.

```js=
db.data.find({sections: {$size: 3}},
{_id: 0, title: 1, sections: 1}).count()
```

Problem:

Connect to our class Atlas cluster from the mongo shell or Compass and view the 100YWeatherSmall.data collection. How many documents in this collection contain exactly two elements in the sections array field?

```js=
db.data.find({sections: {$size: 2}},
{_id: 0, title: 1, sections: 1}).count()
```

$elemMatch
> The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

Problem:

In the M001 class Atlas cluster you will find a database added just for this week of the course. It is called results. Within this database you will find two collections: surveys and scores. Documents in the results.surveys collection have the following schema.

{_id: ObjectId("5964e8e5f0df64e7bc2d7373"),
 results: [{product: "abc", score: 10}, {product: "xyz", score: 9}]}
 
The field called results that has an array as its value. This array contains survey results for products and lists the product name and the survey score for each product.

How many documents in the results.surveys collection contain a score of 7 for the product, "abc"?

```js=
db.surveys.find({results: {$elemMatch: {product: "abc", score: 7}}}).count()
```

$regex
> Selects documents where values match a specified regular expression.
```js=
db.movieDetails.find({}, {_id: 0, "title": 1, "awards.text": 1}).pretty()

db.movieDetails.find({"awards.text": {$regex: /^Won.* /}}, {_id: 0, title: 1, "awards.text": 1}).pretty()

db.movieDetails.find({"awards.text":{$regex: /^Won.*/}}).count()

db.movieDetails.find({"awards.text":{$regex: /^Won.*/}},{_id: 0, title: 1, "awards.text": 1}).pretty()
```

Problem:

Connect to our class Atlas cluster from the mongo shell or Compass and view the results.scores collection.

How many documents contain at least one score in the results array that is greater than or equal to 70 and less than 80?


```js=
db.scores.find({results: {$elemMatch: {$gte:70, $lt: 80}}}).count()
```

###### tags: `mongodb`