show databases# implicitly create dbuse xxx_dbdb.createCollection('users')# INSERTdb.xxxc.insertOne({x: 1}) db.xxxc.insertMany([{}, {}])# QUERY# search in xxx_collection# with status=='Success' and only return name filed# implecitly create collectio and each document's _id fileddb.collection.find({'status': 'Success'}, {'name': 1, 'age': 0})db.collection.find({'status': {'$in': ['A', 'B']}, 'name': 'B'}) # operatordb.collection.find({'com.size': {'$lt': 15}})# for array fielddb.collection.find({'tags': "red"}) # red in tagsdb.collection.find({'tags': ['red', 'black']}) # ['red', 'black'] == tagsdb.collection.find({'tags': {'$all': ['red', 'black']}}) # ['red', 'black'] in tagsdb.collection.find({'tags': {'$lt': 5}}) # with element in tags < 5db.collection.find({'tags': {'$lt': 5, '$gt': 20}}) # OR with element in tags < 5 or > 20db.inventory.find( { 'tags': { '$elemMatch': { '$gt': 22, '$lt': 30 } } } ) # AND multi version of the abovedb.inventory.find( { "tags.1": { '$gt': 25 } } ) # the second element in tags > 25db.inventory.find( { "tags": { '$size': 3 } } ) # len(tags) == 3# project fielddb.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )db.inventory.find({stateus, 'A'}, { item: 1, status: 1, size: { uom: 1 } })# for instock array, return the last onedb.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )cursor = db.collection.find()for item in cursor: print(item)# UPDATEdb.xxxc.updateOne()db.xxxc.updateMany()db.xxxc.replaceOne()# use update operations# $addFields $set $project $unset $replaceRoot $replaceWithdb.students.updateOne( { _id: 3 }, [ { $set: { "test3": 98, modified: "$$NOW"} } ] )db.students2.updateMany( {}, [ { $replaceRoot: { newRoot: { $mergeObjects: [ { quiz1: 0, quiz2: 0, test1: 0, test2: 0 }, "$$ROOT" ] } } }, { $set: { modified: "$$NOW"} } ])db.collection.update() when used with the upsert: true option.db.collection.updateOne() when used with the upsert: true option.db.collection.updateMany() when used with the upsert: true option.db.collection.findAndModify() when used with the upsert: true option.db.collection.findOneAndUpdate() when used with the upsert: true option.db.collection.findOneAndReplace() when used with the upsert: true option.db.collection.save().db.collection.bulkWrite()db.collection.deleteOne()db.collection.deleteMany()db.collection.remove()db.collection.findOneAndDelete()db.collection.findAndModify().db.collection.findAndModify() provides a sort option. The option allows for the deletion of the first document sorted by the specified order.db.collection.bulkWrite().
views
Capped Collections