MongoDB Original Life Order CURD

Learning excerpt from MongoDB Authoritative Guide

Insert

Use insert method

  • This action document automatically generates a'_id'key

>db.foo.insert({"bar" : "baz"})

Batch insert, using batchInsert function

>db.foo.batchInsert([{ "_id" : 0 } , { "_id" : 1 } , { "_id" : 2 }])

The maximum message length currently acceptable to mongodb is 48MB, and if a document insert fails during a bulk insert, all documents before that document will be successfully inserted into the collection, and all documents after that document will fail to insert.

Remove

Using the remove method

//Delete all documents from the foo collection
>db.foo.remove()

//Delete the specified query document as an optional parameter
>db.mailing.list.remove( { "opt-out" : true } )

Using drop() is faster than deleting the collection directly

>db.foo.drop()

Update

Document replacement

{
  "_id": ObjectId("..."),
  "name": "joe",
  "friends": 32,
  "enemies": 2
}

Now you need to update the fields "friends" and "enemies" to the "relationships" subdocument


>var joe = db.users.findOne({"name":joe});
>joe.relationships = {"friends":joe.friends,"enemies":joe.enemies};
{
  "friends":32,
  "enemies":2
}
>joe.username = joe.name;
"joe"
>delete joe.friends;
true
>delete joe.enemies;
true
>delete joe.name;
true
>db.users.update({"name":"joe"},joe);

Updated Documents

{
  "_id":ObjectId("..."),
  "username":"joe",
  "relationships":{
    "friends":32,
    "enemies":2
  }
}

A common error is when a query matches multiple documents and then updates with duplicate'_id'values due to the presence of the second parameter, in which case the'_id' value is used to query

Use Modifier

  • '$inc'modifier uses

When someone visits a page, they find it in the url and use the'$inc'modifier to increase the value of'pagerviews'

{
  "_id":ObjectId("..."),
  "url":"www.lgybetter.com",
  "pagerviews":52
}
>db.analytics.update({"url":"www.lgybetter.com"},{"$inc" : {"pagerviews" : 1}})

Note that when using the modifier,'_id'does not change, and document replacement does

  • '$set'modifier uses

>db.user.update({"_id":ObjectId(...)},{"$set" : {"favorite book" : "War and Peace"}})

The updated document then has the "favorite book" key, if you want to proceed with the modification:

>db.user.update({"_id":ObjectId(...)},{"$set" : {"favorite book" : "Green Eggs and Ham"}})

You can also change to the type of array

  • Use'$unset'to delete this key completely:

>db.user.update({"name":joe},{"$unset" : {"favorite book" : 1}})
  • '$push'modifier uses

    If the array exists,'$push'adds an element to the end of the existing array and creates a new one if the array is not changed

{
  "_id":ObjectId("..."),
  "title":"A blog post",
  "content":"..."
}
>db.blogs.posts.update({"title" : "A blog post"},{"$push" : {
    "comments" : {"name" : "joe","email" : "joe@example.com","content":"nice post."}
}})
>db.blog.posts.findOne()
{
  "_id":ObjectId("..."),
  "title":"A blog post",
  "content":"...",
  "comments": [
    {
      "name":"joe",
      "email":"joe@example.com",
      "content":"nice post"
    }
  ]
}

Note that'$push'creates an array type that can be used to dynamically add data

  • Add more than one data at a time with'$push'and use'$each'

>db.stock.ticker.update({"_id":"GOOG"},{
  "$push" : {"hourly" : { "$each" : [
    562.776,562.790,559.123
  ]}}
})
  • Use'$slice'to fix the maximum length of the array

>db.movies.find({"genre" : "horror"},{
  "$push" : { "top10" : {
      "$each" : ["Nightmare on Elm Street" , "Saw"],
      "$slice" : -10,
      "$sort" : {"rating" : -1}
    }
  }
})

Note that the value of'$slice'should be a negative integer,'$sort' can be used to sort all objects in the array, not only'$slice'or'$sort' with'$push', but also'$each'.

  • Use'$ne'to make the array a data collection

>db.paper.update({"authors cited" : {"$ne" : "Richie"},
  {"$push" : {"authors cited" : "Richie"}}
})
  • A combination of'$addToSet'and'$each' has the same effect as'$ne', but can be used to insert multiple pieces of data at once

>db.users.update({"_id" : ObjectId("...")}, {"$addToSet" :
  {"emails" : {"$each" :
    ["joe@php.net","joe@example.com","joe@python.org"]
  }}
})
  • Delete the array element {'$pop'using'$pop': {key': 1}} from the end of the array, {'$pop': {key': -1}} from the head of the array

  • Use'$pull'to delete elements

>db.lists.update({},{"$pull" : {"todo" : "laundry"}})

Use upsert

upsert is a special update. If no document matches the update criteria, it will be updated with the criteria
Create a new document based on the document.

>db.analytics.update({"url" : "/blog"} , {"$inc" : {"pageviews" : 1}} ,true)
  • Sometimes you need to create a field and assign values to it at the same time you create a document, but the value of that field will not change in all subsequent updates.Use'$setOnInsert'at this point

>db.users.update({} , {"$setOnInsert" : {"createdAt" new Date()}},true)

Update multiple documents

The specific operation values are:

>db.runCommand({getLastError:1}) 

Return results

{
  "err":null,
  "updatedExisting":true,
  "n":5,
  "ok":true
}    

Find

find Getting Started

  • Query all documents under this collection

>db.c.find()
  • Query documents with specific values to add multiple conditions at the same time

>db.users.find({"age" : 20})
>db.users.find({"age" : 20 , "name" : "lgy"})
//Specify the key to return
>db.users.find({} , {"username" : 1,"email" : 1})
//Return results
{
  "_id":ObjectId("..."),
  "username":"lgy",
  "email":"lgy@example.com"
}
  • By query, the key'_id'is returned by default, and if you want no other key to appear, use the following:

>db.users.find({},{"username" : 1,"_id" : 0})
//Return results
{
    "username":"lgy"
}

query criteria

  • Query criteria:

"$lt", $lte", $gt", $gte"are all comparison operators, corresponding to <, <=, >=

//Query 18 to 30 year old users:
>db.users.find({"age" : {"$gte" : 18 , "$lte" : 30}})

'$ne'means not equal to a specific value

//Query all users whose username is not "lgy"
>db.users.find({"username" : {"$ne" : "lgy"}})
  • OR Query:

OR query with'$in'and'$or'

>db.raffle.find({"ticket_no" : {"$in" : [725,542,390]}})

'$nin'is the opposite of'$in'

>db.raffle.find({"$or" : [{"ticket_no" : 725},{"winner" : true}]})
  • Combining the two:

>db.raffle.find({"$or" : [{"ticket_no" : {"$in" : [725,542,300]}},{"winner" : true}]})

$not

'$not'is a meta-conditional sentence, that is, it can be above any other condition.

'$mod'passes in two parameters, the first being used as a divisor and the second to determine if the remainder is this number
>db.user.find({"id_num" : {"$not" : {"$mod" : [5,1]}}})

Specific types of queries

  • null

Null not only matches documents with a null value for a key, it also matches documents without that key

>db.c.find({"z" : null})

If you only want to match documents with null key values, you can use the'$exists'condition:

>db.c.find({"z" : {"$in" : [null], "$exists" : true}})
  • regular expression

>db.users.find({"name" : /joey?/i})
  • Query Array

$all, which can be used to match arrays of multiple elements

//This allows you to find documents that match two elements that exist at the same time
>db.food.find({"fruit" : {"$all" : ["people","banana"]}})

$size is used to query arrays of a specific length

>db.food.find({"furit" : {"$size" : 3}})

$slice is used to return a subset of a matching array element

//Return to the first ten comments, and if you change 10 to -10, the last ten
>db.blog.posts.findOne(criteria,{"comments" : {"$slice" : 10}})

//This operation skips the first 23 elements and returns the 24-33 elements
>db.blog.posts.findOne(criteria,{"comments" : {"$slice" : [23,10]}})

Returns a matching array element

>db.blog.find({"comments.name" : "bob"}, {"comments.$" : 1})
//Return results
{
  "id" : ObjectId("..."),
  "comments" : [
    {
      "name" : "bob",
      "email" : "bob@example.com",
      "content" : "good post"
    }
  ]
}
//Only the first comment will be returned
  • Query embedded documents

There is now such data

{
  "name": {
    "first":"joe",
    "last":"Schmoe"
  },
  "age":45
}

Queries on embedded documents

//Use dot notation to express the meaning of "going inside an embedded document"
>db.people.find({"name.first" : "joe" ,"name.last" : "Schmoe"})

To correctly specify a set of conditions without specifying each key, you need to use'$elematch'

>db.blog.find({"comments" : {$elematch" : {"author" : "joe", "score" : {"$gte" : 5}}}})

cursor

  • Specific operations for cursor queries:

>for(i = 0; i <100; i ++) {
  db.collection.insert({x : i});
}

>var cursor = db.collection.find();

>while(cursor.hasNext()) {
  obj = cursor.next();
  //Output View
}

###limit,skip, and sort

    >db.c.find().limit(3)


    >db.c.find().skip(3)

Keywords: node.js MongoDB PHP Python

Added by Skepsis on Mon, 15 Jul 2019 20:06:20 +0300