Reputation: 95
MongoDB 3.2 has this nice validation feature. However, in this doc it only shows me how to do the validation on first level fields. If I have the following embedded document to insert, how could I set the validation rule?
{"name": {
"first_name": "xx",
"last_name": "yy"
}
}
I've tried the following but it doesn't work,
db.createCollection( "name_collection",
{ validator: { $and:
[
{name.first_name: {$type: "string"}},
{name.last_name: {$type: "string"}}
]
}
)
Thanks in advance.
Upvotes: 3
Views: 3291
Reputation: 8978
Well you have couple errors in your code snippet.
Your db.createCollection doesn't have matching braches. It should look like
db.createCollection("name_collection", {
validator: { $and:[
{'name.first_name': {$type: "string"}},
{'name.last_name': {$type: "string"}}
]}
})
To verify if validation is working or not, try inserting partial data
db.name_collection.insert({name:{first_name:0, last_name:0}})
See I'm just assigning numeric value to first_name and last_name so validation should fail.
After execution of above query, It gives following error.
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
But if I assign text as pasted below, insertion should succeed which does.
db.name_collection.insert({name:{first_name:'f_name', last_name:'l_name'}})
Result:
WriteResult({ "nInserted" : 1 })
Hope this is what are you looking.
Upvotes: 1
Reputation: 48366
Here are the test codes, it works well
> db.createCollection('name', {validator: {$and: [{"name.first_name": {$type: 'string'}}, {"name.last_name": {$type: 'string'}}]}})
{ "ok" : 1 }
It seems you should add ""
to name.last_name
,
Test it with valid data
> db.name.insert({name: {first_name: 'xx', last_name: 'yy'}})
WriteResult({ "nInserted" : 1 })
Test it with invalid data
> db.name.insert({name: {first_name: 'xx', last_name: 3}})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
> db.name.find()
{ "_id" : ObjectId("56e8b644f33ed6e7f3c57f90"), "name" : { "first_name" : "xx",
"last_name" : "yy" } }
Upvotes: 3