M220JS: Chapter 2: User-Facing Backend

MongoDB for JavaScript Developers(Chapter 2 of 4)

Paging

sort()
limit(numPerPage)
skip(page*numPerPage)

Basic Writes

Upsert == Insert + Update


insertOne()
insertMany()

const upsertResult = await theaters.updateOne(
	{
	"location.address": newTheaterDoc.location.address,
	},
	{
	$set: newTheaterDoc,
	},
	{ upsert: true },
)

Write Concerns

严格的情况下,需要确保大多数写入成功再返回成功消息。

How they can provide different level of write durablilty in our application.

// w: num of nodes ack(ed)
writeConcern: {w:1}
  • Only requests an acknowledgement that one node applied the write
  • This is the default writeConcern in MongoDB
writeConcern: {w:"majority"}

0 does ensure that a write was committed by any nodes.

writeConcern: {w:0 }

Basic Updates

updateOne()
updateMany()
const upsertResult = await theaters.updateOne(
	{
		"location.address": newTheaterDoc.location.address,
	},
	{
		$set: newTheaterDoc,
	},
	{ upsert: true },
)

Basic Joins

  • Join two collections of data
    • Movies and comments
  • Use new expressive $lookup
  • Build aggregation in Compass, and then export to language

Pipeline

[
  {
    '$match': {
      'year': {
        '$gte': 1980,
        '$lt': 1990
      }
    }
  },
	{'$lookup': {
      'from': 'comments',
      'let': {
				//
        'id': '$_id'
      },
      'pipeline': [
        {
          '$match': {
            '$expr': {
              '$eq': [
                '$movie_id', '$$id'
              ]
            }
          }
        }, {
          '$count': 'count'
        }
      ],
      'as': 'movie_comments'
    }
  }
]

The only way we can use fields from the movies collection in the pipeline is by defining those variables in the let expression.

Basic Deletes

When we perform a delete:

  • Collection data will be changed
  • Indexes will be updated
  • Entries in the oplog(for replication) will be added
//deleteOne deletes the first matching document in $natural order.
deleteOne()
// deleteMany deletes multiple matching documents in one operation.
deleteMany()