0

I am fetching data from MongoDB using java program. MongoDB data contains:

{
"gender": "female",
"city": "ABC",
"phone": "+1 (995) 441-2988",
"email": "[email protected]",
"date": "2015-08-11T15:55:00 -06:-30",
"age": 37,}

Need to validate data like city should be string value, age should be integer, etc. Is there any quick way to use MongoDB queries in java to validate this?

2
  • Use $type Commented Aug 18, 2015 at 5:48
  • How to use it in java? Commented Aug 18, 2015 at 6:10

2 Answers 2

1

MongoDB $type selects the documents where the value of the field is an instance of the specified numeric BSON type.

As per your document structure date field is not actual ISODATE it looks like String so it's data type 2 and age default data type 1 like double so your java code as

BasicDBObject query = new BasicDBObject();
query.put("gender",new BasicDBObject("$type",2));
query.put("city",new BasicDBObject("$type",2));
query.put("phone",new BasicDBObject("$type",2));
query.put("email",new BasicDBObject("$type",2));
query.put("date",new BasicDBObject("$type",2));
query.put("age", new BasicDBObject("$type",1));

    DBCursor cursorDoc  =  collection.find(query);
    while (cursorDoc.hasNext()) {
        BasicDBObject object = (BasicDBObject) cursorDoc.next();
        System.out.println(object);
    }
Sign up to request clarification or add additional context in comments.

6 Comments

if I have "city" : "ABC123", what query should be used to get city having only characters,it does not contain any digit.
You want to run same query in mongo shell?
if I give city as abc123 it is considering it as string. So it is giving that record as valid record
yes it is valid record because you entered city like city:"abc123" is String not number if you insert city:123 then it invalid because 123 consider as number not string , If you confused about data type then read this mongo type it will helpful to find out which documents are valid or not
can we use $regex to check number or string ?
|
0

In the upcoming Mongo 3.2 version they added document validation (slides).

You can specify validation rules for each collection, using validator option using almost all mongo query operators (except $geoNear, $near, $nearSphere, $text, and $where).

Based on your requirements, it is enough to achieve what you want with just checking type. You can read more here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.