Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.