MongoDB - CRUD Part 2
- Limits
- No document can exceed 16MB
- The depth of nesting documents within documents is limited at 100 levels of nesting.
- documents containing duplicate field names are not supported
- HOWEVER, you may not get an error. The second occurrence of the field will overwrite the value of the first.
- Inserting one or multiple documents
db.collection.find(query, projection)
- JSON Datatypes
- String: Refers to plain text
- Number: Consists of all numeric fields
- int (32-bit),
- long (64 bit),
- double (64 bit),
- decimal (128 bit floating point)
- Boolean: Consists of
true
orfalse
- Object: nested or embedded documents (embedded JSON ) objects
- Array: Collection of fields
- unlimited number of elements, BUT total size of a single document cannot exceed 16MB
- Null: Special value to denote fields without any value
- JSON validators
- e.g., https://jsonlint.com/
- MongoDB’s BSON format supports Date types, all are UTC (i.e., no time zone
info is kept)
- the JSON spec has no date type.
new Date()
results in UTCvar date = Date()
produces a date/time in local timezone
more CRUD
- empty filters and non-existant fields work the same
// These all produce the same output
db.comments.findOne()
db.comments.findOne({})
db.comments.findOne({"foo":null})
distinct
selects all the unique values that a field holds
db.movies.distinct("rated", {"year" : 1994})
[
'G', 'NOT RATED',
'PG', 'PG-13',
'R', 'TV-14',
'TV-PG', 'UNRATED'
]
- More logical ops
db.movies.find(
{"released" :
{$gte: new Date('2015-01-01')}
}
).count()
811
// Before 2000-01-01
db.movies.find(
{"released" :
{$lt : new Date('2000-01-01')}
}
).count()
9262
// $in and $nin (not in)
db.movies.find( {"rated" : {$in : ["UNRATED", "R" ]} } )
6288
// list the genres of the movies Cate Blanchett has been in
db.movies.distinct("genres", {"cast" : "Cate Blanchett"})
// then list the movie title and year only (projection)
db.movies.find(
{"cast" : "Cate Blanchett"},
{"title":1,
"year":1,
"_id":0}
)
// Use regex to find movies with "Paris" in the title
db.movies.find(
{"title" :
{$regex :"Paris"}
},
{"title":1,"_id":0}
)
// at the front
db.movies.find(
{"title" :
{$regex :"^Paris"}
},
{"title":1,"_id":0}
)
// at the end
db.movies.find(
{"title" :
{$regex :"Paris$"}
},
{"title":1,"_id":0}
)
Case insensitive queries too.
db.movies.find(
{"title" :
{$regex :"Paris$"}
},
{"title":1,"_id":0}
)
Sorting
db.movies.find(
{"cast" : "Cate Blanchett"},
{"title" : 1, "_id" :0}
).sort(
{"title" : 1}
)
// or even fancier
db.movies.find(
{"type":"movie"},
{"title":1,"cast":1,"_id":0}
).sort(
{"cast.0":-1,"title":1}
)
Inserting
//
// db.collection.insert({ <new field:value pair>, ...} )
// db.collection.insertMany([
// {"field1":"AA", "field2":"BB", ...} ,
// {"field1":"CC", "field2":"DD", ...} ,
// {"field2":"FF", "field1":"EE", ...}
// ]
use test
db.pile.insertMany([
{"field1":"AB", "field2":"CD"} ,
{"field1":"EF", "field2":"GH"} ,
{"field2":"KL", "field1":"ER"}
])
Updating existing fields or adding new ones
// three of the ways to update:
//
// db.collection.updateOne(<filter>, <update>, <options>)
// db.collection.updateMany(<filter>, <update>, <options>)
// db.collection.replaceOne(<filter>, <update>, <options>)
db.pile.updateOne(
{ "field1":"ER" },
{ "$set": {"field2":"YZ", "field3":"foople"}
}
)
and Deleting
db.pile.deleteOne(
{ "field1": {"$regex": "^E"}
}
)
Using your own _id
field
You can make your own
db.newcoll.insertMany([
{"_id": 1, "flavor": "chunky monkey"},
{"_id": 2, "flavor": "cherry garcia"},
{"_id": 3, "flavor": "half baked"},
{"_id": 4, "flavor": "phish food"}
])
but be careful: duplicate keys can happen!
db.newcoll.insert({"_id":2, flavor: "chubby hubby"})
MongoServerError: E11000 duplicate key error collection: test.newcoll index: _id_ dup key: { _id: 2 }
What about multiple updates to one field?
The last update wins!
test> db.newcoll.find()
[
{ _id: 1, flavor: 'chunky monkey' },
{ _id: 2, flavor: 'cherry garcia' },
{ _id: 3, flavor: 'half baked' },
{ _id: 4, flavor: 'phish food' }
]
test> db.newcoll.insertOne(
... { "_id": 6, "flavor": "cheeseburger", "calories": 350, "flavor": "kumquat surprise"
... }
... )
{ acknowledged: true, insertedId: 6 }
test> db.newcoll.find()
[
{ _id: 1, flavor: 'chunky monkey' },
{ _id: 2, flavor: 'cherry garcia' },
{ _id: 3, flavor: 'half baked' },
{ _id: 4, flavor: 'phish food' },
{ _id: 6, flavor: 'kumquat surprise', calories: 350 }
]
getTimestamp()
on the ObjectId
returns the document insertion time.