Mongodb document validation - mongodb

I need your help on mongodb document validation. I am trying to create the mongodb document structure below:
db.createCollection("People2", {
validator: {
$and: [
{
Identity: {
Number: {
$type: "string",
$exists: true
},
Type: {
$type: "string",
$exists: true
}
}
},
{
"lastName": {
$type: "string",
$exists: true
}
},
{
"email": {
$type: "string",
$exists: true,
}
},
{
UserVerification: { $in: [ "Rejected", "Validated" ] }
}
]
}
})
Below command to test document insertion:
db.People2.insert(
{
IdentityCard: {
Number: "#1234",
Type: "typeA"
},
lastName: "toto",
email: "toto#mydom.com",
UserVerification: "Validated"
}
);
But a get this error:
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
I think The problem come from the object "Identity" validation declaration which is not correct.

Please try this and your statement is using IdentityCard but not Identity.
db.createCollection("People2", {
validator: {
$and: [
{
"IdentityCard.Number": {
$type: "string",
$exists: true
},
"IdentityCard.Type": {
$type: "string",
$exists: true
}
},
{
"lastName": {
$type: "string",
$exists: true
}
},
{
"email": {
$type: "string",
$exists: true,
}
},
{
UserVerification: { $in: [ "Rejected", "Validated" ] }
}
]
}
})

Related

MongoDB Update many item in nested object by array of Id

How to update some of the nested objects found by thair Id in MongoDB.
In the below case, only the first Item will be updated!
Update all nested objects in updateMany.
"Parent":[{
"Child": [{
"_id": 5f26fad5b34a304dfc1dd16a,
"isActive": false,
}, {
"_id": 5f26fad5b34a304dfc1dd16c,
"isActive": false,
}, {
"_id": 5f2705281b42ea2de8b7c9e2,
"isActive": false,
}
],
"name": "Paretn1"
},
]
parent.updateMany(
{
"child._id": { $in: [ObjectId('5f26fad5b34a304dfc1dd16a'), ObjectId('5f26fad5b34a304dfc1dd16c')
]}
},
{ $set: { "child.$.isActive": true } },
{ multi: true },
() => {
console.log('done')
}
);
You can do as below
parent.updateMany(
{
"child._id": { $in:
[ObjectId('5f26fad5b34a304dfc1dd16a'),
ObjectId('5f26fad5b34a304dfc1dd16c')
]}
},
{ $set: { "child.$[element].isActive": true } },
{ "arrayFilters": [{ "elem._id": {'$in' :[
ObjectId('5f26fad5b34a304dfc1dd16a'),
ObjectId('5f26fad5b34a304dfc1dd16c')] } }], "multi": true },
() => {
console.log('done')
}
);

Query datevalue of a inner Array element

Need help with some MongoDB query:
The document I have is below and I am trying to search based on 2 conditions
The meta.tags.code = "ABC"
Its LastSyncDateTime should
meta.extension.value == "" (OR)
the meta.extension.value is less than meta.lastUpdated
Data :
{
"meta" : {
"extension" : [
{
"url" : "LastSyncDateTime",
"value" : "20190206-00:49:25.694"
},
{
"url" : "RetryCount",
"value" : "0"
}
],
"lastUpdate" : "20190207-01:21:41.095",
"tags" : [
{
"code" : "ABC",
"system" : "type"
},
{
"code" : "XYZ",
"system" : "SourceSystem"
}
]
}
}
Query:
db.proc_patients_service.find({
"meta.tags.code": "ABC",
$or: [{
"meta.extension.value": ""
}, {
$expr: { "$lt": [{ "mgfunc": "ISODate", "params": [{ "$arrayElemAt": ["$meta.extension.value", 0] }] }, { "mgfunc": "ISODate", "params": ["$meta.lastUpdate"] }] }
}]
})
But it is only fetching ABC Patients whose LastSyncDateTime is empty and ignores the other condition.
Using MongoDB Aggregation, I have converted your string to date with operator $dateFromString and then compare the value as per your criteria.
db.proc_patients_service.aggregate([
{ $match: { "meta.tags.code": "ABC", } },
{ $unwind: "$meta.extension" },
{
$project: {
'meta.tags': '$meta.tags',
'meta.lastUpdate': { '$dateFromString': { 'dateString': '$meta.lastUpdate', format: "%Y%m%d-%H:%M:%S.%L" } },
'meta.extension.url': '$meta.extension.url',
'meta.extension.value': {
$cond: {
if: { $ne: ["$meta.extension.value", "0"] }, then: { '$dateFromString': { 'dateString': '$meta.extension.value', format: "%Y%m%d-%H:%M:%S.%L" } }, else: 0
}
}
}
},
{
$match: {
$or: [
{ "meta.extension.value": 0 },
{ $expr: { $lt: ["$meta.extension.value", "$meta.lastUpdate"] } }
]
}
},
{
$group: { _id: '_id', 'extension': { $push: '$meta.extension' }, "lastUpdate": { $first: '$meta.lastUpdate' }, 'tags': { $first: '$meta.tags' } }
},
{
$project: { meta: { 'extension': '$extension', lastUpdate: '$lastUpdate', 'tags': '$tags' } }
}
])

How do I get the current validator of a mongo collection?

How do I get the current validator of a mongo collection?
Or is there no way, and I just need to overwrite it?
You can get it with the db.getCollectionInfos() method.
Example:
Create a collection in an empty database:
db.createCollection( "contacts",
{
validator: { $or:
[
{ phone: { $type: "string" } },
{ email: { $regex: /#mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
},
validationAction: "warn"
}
)
{ "ok" : 1 }
Run the command:
db.getCollectionInfos()[0].options.validator
Result:
{
"$or" : [
{
"phone": {
"$type": "string"
}
},
{
"email": {
"$regex": /#mongodb\.com$/
}
},
{
"status": {
"$in": [
"Unknown",
"Incomplete"
]
}
}
]
}
The validator is found as an object in the options object.

Mongo shell insert statement for array of objects failing validation

I have the below collection schema which has been created and passed the validation:
db.createCollection("Settings",
{ validator: { $or:
[
{cID:{ $type: "int" } },
{sID : { $type: "int" } },
{default :
[
{default1:
{
name : { $type: "string" },
priority : { $type: "string" },
autoMoveToCompleted : { $type: "string" },
notifyInAdvance : { $type: "string" }
}
},
{default2 :
{
name : { $type: "string" },
priority : { $type: "string" },
autoMoveToCompleted : { $type: "string" }
}
}
]
},
{applied: [
{applied1:
{ name : { $type: "string" },
priority : { $type: "string" },
autoMoveToCompleted : { $type: "string" },
notifyInAdvance : { $type: "string" }
}
},
{applied2 :
{
name : { $type: "string" },
priority : { $type: "string" },
autoMoveToCompleted : { $type: "string" }
}
}
]}
]
}
}
)
But, I cannot generate a valid insert statement for above schema as it involves arrays. I tried to find the resolution in google but could not find anything related to prepare an insert statement similar to above schema.
Please help generating the insert statement for this schema for one mongo document, to run the insert query on mongo shell.
I only can propose to change validation schema like:
db.createCollection("Settings",
{ validator: { $or:
[
{cID:{ $type: "int" } },
{sID : { $type: "int" } },
{"default.default1.name" : { $type: "string" },
"default.default1.priority" : { $type: "string" },
"default.default1.autoMoveToCompleted" : { $type: "string" },
"default.default1.notifyInAdvance" : { $type: "string" },
"default.default2.name" : { $type: "string" },
"default.default2.priority" : { $type: "string" },
"default.default2.autoMoveToCompleted" : { $type: "string" }
}
]
}
}
)
It must work

MongoDB document validation fail

Trying to test the validation of the document below:
db.createCollection("Users", {
validator: {
$and: [
{
Uid: {
$type: "string",
$exists: true
}
},
{
"Doc.Name": { $type: "string", $exists: true},
"Doc.Files": [
{
"$ref": { $in: [ "fs.files" ] },
"$id": { $type: "objectId", $exists: true },
"$db": { $in: [ "mydb" ] }
}
]
}
]
}
})
With command of insertion:
db.Users.insert({
Uid: "ABCDFE123m",
Doc: {
Name: "12hgf123",
Files: [
{
$ref:"fs.files",
$id: ObjectId("5910e46b24f3f7057c4088a8"),
$db: "mydb"
},
{
$ref:"fs.files",
$id: ObjectId("4010e46b24f3f7057c408806"),
$db: "mydb"
}
]
}
})
I get the following error:
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
Enable to validate the document insertion. Someone can help me? Look like i forget something.
Regards