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
Related
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' } }
}
])
I have a Mongodb Data which looks like this
{
"userId" : "123",
"dataArray" : [
{
"scheduledStartDate" : ISODate("2018-08-30T11:34:36.000+05:30"),
"scheduledEndDate" : ISODate("2018-08-30T11:34:36.000+05:30"),
"Progress" : 0,
"ASD":""
},
{
"scheduledStartDate" : ISODate("2018-09-22T11:34:36.000+05:30"),
"scheduledEndDate" : ISODate("2018-10-01T11:34:36.000+05:30"),
"Progress" : 0,
"ASD":ISODate("2018-08-30T11:34:36.000+05:30"),
}
],
"userStatus" : 1,
"completionStatus" : "IP",
}
I want to find those document where condition is something like this
(PROGRESS<100||(PROGRESS==100&&ASD not exists)).
This should get you going ($elemMatch):
db.collection.find({
dataArray: {
$elemMatch: {
$or: [
{ Progress: { $lt: 100 } },
{ $and: [
{ Progress: { $eq: 100 } },
{ ASD: { $exists: false } }
]}
]
}
}
})
UPDATE based on your comment - this is even easier:
db.collection.find({
$or: [
{ "dataArray.Progress": { $lt: 100 } },
{ $and: [
{ "dataArray.Progress": { $eq: 100 } },
{ "dataArray.ASD": { $exists: false } }
]}
]
})
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.
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" ] }
}
]
}
})
Basically, I am new to MongoDB and learning from documents. I wanted to use validator, validationLevel, validationAction while defining a collection in MongoDB. So I can get an error if validated data is not inserted or updated. I have followed this document for reference. However, I got success in defining collection but when I add the wrong record it doesn't give me error like it is mentioned in documents. Everytime new record is getting inserted. Can you guys please help me in this whats wrong with my code.
I am using the following command to create a collection
db.createCollection( "contacts",
{
validator: { $and:
[
{ phone: { $type: "string" } },
{ email: { $regex: /#mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
],
validationAction: "error"
}
}
)
I have also used the same command with validationLevel to strict like below but it also didn't work out.
db.createCollection( "contacts",
{
validator: { $and:
[
{ phone: { $type: "string" } },
{ email: { $regex: /#mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
],
validationAction: "error",
validationLevel: "strict"
}
}
)
A command I used to insert record is as below
db.contacts.insert( { name: "Amanda", status: "Updated" } )
Below is the expected output as per the document.
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
But I end up getting success output as below
WriteResult({ "nInserted" : 1 })
I guess you validation rule is not applied to the collection. You can check for the same using
getCollectionInfos({name:'constacts'})
here is the link.
Error is in the validationAction and validationLevel.
use this
db.createCollection( "contacts", { validator:
{ $and:
[
{ phone: { $type: "string" } },
{ email: { $regex: /#mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
},
validationLevel : "strict",
validationAction : "error"
}
)
insted of
db.createCollection( "contacts",
{
validator: { $and:
[
{ phone: { $type: "string" } },
{ email: { $regex: /#mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
],
validationAction: "error",
validationLevel: "strict"
}
}
)
Quote from documentation:
You cannot specify a validator for collections in the admin, local,
and config databases. You cannot specify a validator for system.*
collections.
https://docs.mongodb.com/v3.2/reference/method/db.createCollection/