Skip to content

Instantly share code, notes, and snippets.

@kennwhite
Last active July 9, 2019 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kennwhite/7f295f44cc9c9d5085361a7f1d519742 to your computer and use it in GitHub Desktop.
Save kennwhite/7f295f44cc9c9d5085361a7f1d519742 to your computer and use it in GitHub Desktop.
Some notes on validating embedded/nested document fields on MongoDB
// See: https://jira.mongodb.org/browse/SERVER-31493
//
// Most drivers will actively block "." in attempts to store documents (see first insert example below)
// but dots are fine to use for queries. Also, nested documents have to be specified carefully
// for jsonSchema document validation
//
> use schematest
switched to db schematest
>
>
> db.createCollection("students", {
... validator: {
... $jsonSchema: {
... bsonType: "object",
... properties: {
... "name": { bsonType: "string" },
... "address": {
... properties: {
... "street" : { bsonType: "string" },
... "city" : { bsonType: "string" },
... "zip" : { bsonType: "string" },
... }
... }
... }
... }
... }
... })
{ "ok" : 1 }
>
>
> db.students.insert({ name: 'fred', 'address.street': '123 main', 'address.city': 'Omaha', 'address.zip': '90210' })
WriteResult({ "nInserted" : 1 })
>
> db.students.insert({ name: 'fred', address: { street: '123 main', city: 'Omaha', zip: '90210' } })
WriteResult({ "nInserted" : 1 })
>
> db.students.find().pretty()
{
"_id" : ObjectId("5d24cace13fbcc6c3297025a"),
"name" : "fred",
"address.street" : "123 main",
"address.city" : "Omaha",
"address.zip" : "90210"
}
{
"_id" : ObjectId("5d24caba13fbcc6c32970259"),
"name" : "fred",
"address" : {
"street" : "123 main",
"city" : "Omaha",
"zip" : "90210"
}
}
>
> db.students.find({ 'address.zip' : '90210' }).pretty()
{
"_id" : ObjectId("5d24caba13fbcc6c32970259"),
"name" : "fred",
"address" : {
"street" : "123 main",
"city" : "Omaha",
"zip" : "90210"
}
}
>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment