How to get object from MongoDb using criteria api in java - java

I want to get result where varifiedDate inside secondaryParents is not 0. How can I achieve this?
DB Structure:
{
"_id" : ObjectId("577a151859defb33c0f8bf4a"),
"_class" : "com.nv.tracker.db.model.User",
"parentId" : NumberLong(1000004),
"userId" : NumberLong(1000005),
"firstName" : "Pranav",
"lastName" : "Rathore",
"addr" : {
"address" : "",
"landmark" : "",
"city" : "",
"state" : "",
"country" : ""
},
"email" : "ashish.dubey#newvisionsoftware.in",
"mobile" : "7879066069",
"createdDate" : ISODate("2016-07-04T07:49:44.000Z"),
"activeStatus" : false,
"imagePath" : "http://172.20.0.210:8080/nvtracker/rest/resource/image/1000005",
"deviceId" : "78 79 066069",
"isSuperUser" : false,
"dob" : "1468348200000",
"checkAndriodOrIos" : 0,
"isLogin" : false,
"otp" : 0,
"batteryLevel" : 30,
"locationInterval" : 60,
"deviceSpeed" : 45,
"primaryMobile" : "9039101994",
"secondaryMobile1" : "9039101994",
"secondaryMobile2" : "",
"primaryEmail" : "ashish.dubey#newvisionsoftware.in",
"secondaryEmail1" : "abb#hh.con",
"secondaryEmail2" : "",
"isVerified" : false,
"currentBatteryLevel" : 0,
"currentSpeed" : 0,
"subscriptionExpDate" : NumberLong(1498132426000),
"enableNotification" : 1,
"enableTakeOffAlert" : 0,
"deleted" : false,
"hasExternalDevice" : false,
"secondaryParents" : {
"1000003" : {
"secondaryparentId" : NumberLong(1000003),
"varifiedDate" : NumberLong(14676286792586),
"addedDate" : NumberLong(1467628679286),
"secreteCode" : "18716"
},
"1000004" : {
"secondaryparentId" : NumberLong(1000004),
"varifiedDate" : NumberLong(0),
"addedDate" : NumberLong(1467628679286),
"secreteCode" : "18716"
}
}
}
I want to get the user where varifiedDate inside secondaryParents is not 0.
Please suggest how I can achieve this. Also provide the best tutorial for 'mongodb using java' with criteria API.

Related

Junit test cases are passing in eclipse but during maven build its failed and it is showing some encoding error in json file like comparison error

Here is my test case and I am individually pasing this junit it is passing but when I am doing maven build it is showing some encoding error in json file, Please check the error message I provide in below
#Test
public void testRemoveEmoji() throws Exception {
Items items = getSampleItems("/json/ItemObjectWithEmojiContent.json");
List<Item> itemList = items.getItemsList();
for(Item item : itemList) {
assertNotNull(item);
this.starcImportProcessor.removeEmojis(item);
assertEquals("(Open -> In Progress -> Open -> Closed)", item.getDescription());
for(ItemComment itemComments : item.getItemComments()) {
assertEquals("Test comment", itemComments.getComment());
}
}
getSampleItems code :
private Items getSampleItems(final String path) throws JsonParseException, JsonMappingException, IOException {
Items downloadedItems = new Items();
JSONArray inputWorkitem = new JSONArray(new String(getJSONFromFile(path)));
final ObjectMapper objectMapper = new ObjectMapper();
List<Item> items = objectMapper.readValue(inputWorkitem.toString(), new TypeReference<List<Item>>() {});
downloadedItems.setItemsList(items);
return downloadedItems;
}
private static byte[] getJSONFromFile(final String jsonFilePath) throws IOException {
Resource resource = new ClassPathResource(jsonFilePath);
File file = resource.getFile();
return Files.readAllBytes(file.toPath());
}
Here is json file :
[
{
"id" : 233565,
"name" : "Hafmap DaimlerBosch Test4 CRL Reject",
"createdAt" : "2020-09-29T16:07:23.918",
"modifiedAt" : "2021-07-08T19:03:12.477",
"version" : "15",
"description" : "(Open -> 😀In Progress -> Open -> Closed)",
"descriptionFormat" : "Wiki",
"assignedAt" : "2020-10-01T15:09:26.022",
"typeName" : "Bug",
"endDate" : "2020-10-08T14:40:00.000",
"closedAt" : "2020-10-08T14:40:34.385",
"ordinal" : 0,
"createdBy" : {
"id" : 1255,
"name" : "CHRBOOT",
"type" : "UserReference",
"email" : "christian.bootz#daimler.com",
"value" : null
},
"modifiedBy" : {
"id" : 3,
"name" : "computed.update",
"type" : "UserReference",
"email" : "codebeamer#intland.com",
"value" : null
},
"tracker" : {
"id" : 269438,
"name" : "Change Request Light",
"type" : "TrackerReference",
"email" : null,
"value" : null
},
"priority" : {
"id" : 0,
"name" : "Unset",
"type" : "ChoiceOptionReference",
"email" : null,
"value" : null
},
"status" : {
"id" : 7,
"name" : "Closed",
"type" : "ChoiceOptionReference",
"email" : null,
"value" : null
},
"severities" : [ {
"id" : 3,
"name" : "VoCA Prio 3",
"type" : "ChoiceOptionReference",
"email" : null,
"value" : null
} ],
"resolutions" : [ ],
"children" : [ ],
"subjects" : [ ],
"assignedTo" : [ {
"id" : 3463,
"name" : "PID8CBD",
"type" : "UserReference",
"email" : "christian.bootz#daimler.com",
"value" : null
} ],
"owners" : null,
"comments" : [ {
"id" : 675988,
"name" : "attachment mit leerzeichen.txt",
"type" : "CommentReference",
"email" : null,
"value" : null
}, {
"id" : 675990,
"name" : "Comment-1601992066937",
"type" : "CommentReference",
"email" : null,
"value" : null
}, {
"id" : 675991,
"name" : "Comment-1601992069782",
"type" : "CommentReference",
"email" : null,
"value" : null
} ],
"categories" : [ ],
"platforms" : [ ],
"customFields" : [ {
"fieldId" : 1001,
"name" : "Sync Allowed",
"values" : [ {
"id" : 1,
"name" : "Supplier External Tool",
"type" : "ChoiceOptionReference",
"email" : null,
"value" : null
} ],
"type" : "ChoiceFieldValue",
"value" : null
}, {
"fieldId" : 1003,
"name" : "Top Ten",
"values" : [ {
"id" : 2,
"name" : "No",
"type" : "ChoiceOptionReference",
"email" : null,
"value" : null
} ],
"type" : "ChoiceFieldValue",
"value" : null
}, {
"fieldId" : 1012,
"name" : "Supplier Status",
"values" : [ {
"id" : 7,
"name" : "Supplier Closed",
"type" : "ChoiceOptionReference",
"email" : null,
"value" : null
} ],
"type" : "ChoiceFieldValue",
"value" : null
}, {
"fieldId" : 1015,
"name" : "Verification By Test Group",
"values" : [ {
"id" : 2,
"name" : "No",
"type" : "ChoiceOptionReference",
"email" : null,
"value" : null
} ],
"type" : "ChoiceFieldValue",
"value" : null
}, {
"fieldId" : 1019,
"name" : "Closing Reason",
"values" : [ {
"id" : 6,
"name" : "No Defect / Issue",
"type" : "ChoiceOptionReference",
"email" : null,
"value" : null
} ],
"type" : "ChoiceFieldValue",
"value" : null
}, {
"fieldId" : 1020,
"name" : "Reject Reason",
"values" : [ {
"id" : 4,
"name" : "Not Reproducible",
"type" : "ChoiceOptionReference",
"email" : null,
"value" : null
} ],
"type" : "ChoiceFieldValue",
"value" : null
}, {
"fieldId" : 1028,
"name" : "Supplier",
"values" : [ {
"id" : 594222,
"name" : "Supplier_Bosch_MAP_ECU",
"type" : "UserGroupReference",
"email" : null,
"value" : null
} ],
"type" : "ChoiceFieldValue",
"value" : null
}, {
"fieldId" : 10000,
"name" : "DEFAULT_PERMISSION_1",
"values" : null,
"type" : "TextFieldValue",
"value" : "1"
}, {
"fieldId" : 10002,
"name" : "Created On Date",
"values" : null,
"type" : "DateFieldValue",
"value" : "2020-09-29T02:00:00.000"
}, {
"fieldId" : 10006,
"name" : "Domain",
"values" : null,
"type" : "TextFieldValue",
"value" : "Automated driving"
}, {
"fieldId" : 10007,
"name" : "Supplier ID",
"values" : null,
"type" : "TextFieldValue",
"value" : "DYMAPDAIEX-155919"
}, {
"fieldId" : 10024,
"name" : "Last Status Change",
"values" : null,
"type" : "DateFieldValue",
"value" : "2020-09-29T18:07:23.000"
}, {
"fieldId" : 10026,
"name" : "DEFAULT_PERMISSION_READONLY_INPROGRESS",
"values" : null,
"type" : "TextFieldValue",
"value" : "1"
} ],
"attachmentData" : [ {
"id" : 675988,
"name" : "attachment mit leerzeichen.txt",
"description" : null,
"descriptionFormat" : "PlainText",
"createdAt" : "2020-10-06T13:47:45.956",
"createdBy" : {
"id" : 3463,
"name" : "PID8CBD",
"type" : "UserReference",
"email" : "christian.bootz#daimler.com",
"value" : null
},
"modifiedAt" : "2020-10-06T13:47:45.956",
"modifiedBy" : {
"id" : 3463,
"name" : "PID8CBD",
"type" : "UserReference",
"email" : "christian.bootz#daimler.com",
"value" : null
},
"version" : 1,
"size" : 317,
"md5" : "A2DE48D274A08AD80D19E8829D0093D4",
"filePath" : null
} ],
"itemComments" : [ {
"id" : 675990,
"name" : "Comment-1601992066937",
"createdAt" : "2020-10-06T13:47:46.937",
"modifiedAt" : null,
"version" : "1",
"createdBy" : {
"id" : 3463,
"name" : "PID8CBD",
"type" : "UserReference",
"email" : "christian.bootz#daimler.com",
"value" : null
},
"modifiedBy" : null,
"comment" : "😀Test comment",
"commentFormat" : "PlainText",
"parent" : null,
"attachments" : [ ]
} ]
}
]
Here is the error when i am doing maven build here some encoding error it is showing:
Could you please help me out how to resolve this issue
testRemoveEmoji(com.bosch.edexas.starc.processor.STARCImportProcessorTest) Time elapsed: 0.008 sec <<< FAILURE!
org.junit.ComparisonFailure: expected:<(Open -> []In Progress -> Open ...> but was:<(Open -> **[😀]**In Progress -> Open ...>
at org.junit.Assert.assertEquals(Assert.java:125)
at org.junit.Assert.assertEquals(Assert.java:147)
at com.bosch.edexas.starc.processor.STARCImportProcessorTest.testRemoveEmoji(STARCImportProcessorTest.java:195)
OpenJDK 64-Bit Server VM warning: ignoring option UseSplitVerifier; support was removed in 8.0
Results :
Failed tests:
STARCImportProcessorTest.testRemoveEmoji:195 expected:<(Open -> []In Progress -> Open ...> but was:<(Open -> **[????]**In Progress -> Open ...>
Please do the following when you are trying to make a new String() when your getJSONFromFile(path) returns a byte[] array.
new String(getJSONFromFile(path), StandardCharsets.UTF_8);

how to interrogate mongoDB data using java?

I need to program an OLAP cube in java, and i have a mongoDB DataBase, i want to interrogate my date using this request:
"select custkey from customer where region=afriqua"
the question is how can i use java instructions to get my data from the collections "customer" which is included in the global collection "cube"
PS: I want to get the resultat of the query.
i'm using a NetBeans IDE 8.2 for codding in java ,and my NoSQL database in MOngoDB 3.11.0.
{ "_id" : ObjectId("5cdc6510af5e07bbde44cade"),
"LineOrder" : [
{ "CustKey" : 10, "SupKey" : 2, "PartKey" : 1360, "DateKey" : 200124, "Quantity" : 201578, "Tax" : 700 },
{ "Orderkey" : 20165, "Linenumber" : 5487, "Custkey" : 12, "Partkey" : 102, "Supkey" : 3, "Orderdate" : "May14,2016", "Shippriority" : 40, "Quantity" : 105, "Extebdedprice" : 1480620, "Ordertotalprice" : 11689695, "Discount" : 21, "Revenue" : 95981, "Supplycost" : 4, "Tax" : 198754, "Commdate" : 201647, "shipmode" : "mail" }
] }
{ "_id" : ObjectId("5cdc653eaf5e07bbde44cae3"),
"Date" : [
{ "DateKey" : 201948, "Date" : "April8,2019", "Dayofweek" : "Monday", "Month" : "April", "Year" : 2019, "Yearmonthnum" : 20194, "Yearmonth" : "Apr2019", "Daynuminweek" : 2, "Daynuminmonth" : 8, "Daynuminyear" : 98, "Monthnuminyear" : 4, "Weeknuminyear" : 15, "Lastdayinweekfl" : 2, "Lastdayinmonthfl" : 3, "Sellingseason" : "winter", "Holidayfl" : 1, "Weekdayfl" : 1 },
{ "DateKey" : 201965, "Date" : "May21,2019", "Dayofweek" : "Thusdey", "Month" : "May", "Year" : 2019, "Yearmonthnum" : 20195, "Yearmonth" : "May2019", "Daynuminweek" : 3, "Daynuminmonth" : 15, "Daynuminyear" : 101, "Monthnuminyear" : 5, "Weeknuminyear" : 21, "Lastdayinweekfl" : 2, "Lastdayinmonthfl" : 3, "Sellingseason" : "spring", "Holidayfl" : 2, "Weekdayfl" : 1 }
] }
{ "_id" : ObjectId("5cdc6550af5e07bbde44cae8"),
"customer" : [
{ "CustKey" : 5, "Name" : "Aleksender Bill", "Address" : "jFKRE3kiytrdf", "citys" : [ { "city" : "Vietnam xyz", "Nation" : "Vietnam", "Region" : "Asia" } ] },
{ "CustKey" : 10, "Name" : "Mohamed Dawed", "citys" : [ { "City" : "Draria", "Nation" : "Algeria", "Region" : "Afriqua" } ] },
{ "CustKey" : 12, "Name" : "George", "Nation" : "Canada" }
] }
{ "_id" : ObjectId("5cdc6563af5e07bbde44caed"),
"part" : [
{ "PartKey" : 1360, "Name" : "khaki chocolat", "Mfgr" : "mfgr#5", "size" : 31, "Color" : "medieum", " Categories" : [ { "Category" : "mfgr#56", "type" : "standar burnishe steel", "container" : "jumbo case" } ] },
{ "PartKey" : 1400, "Name" : "zzd nnn", "Mfgr" : "fgr#8", "size" : 10, "Categories" : [ { "Category" : "fgr#10", "type" : "xxxx", "container" : "jumbo" } ] },
{ "PartKey" : 102, "Color" : "edieum", "Categories" : [ { "Category" : "fgr#56", "type" : "yyy", "container" : "jj ccc" } ] }
] }
I try whith this code,but it doesn't work
import com.mongodb.MongoClient;
import com.mongodb.*;
public class Mongoconn {
public static void main(String[] args) {
// connect java to mongoDB
MongoClient mongoClient = new MongoClient("localhost", 27017);
System.out.println("server connection successfully done");
//choisir la base de données
DB dbs=mongoClient.getDB("ssb");
System.out.println("connected to database:"+dbs.getName());
// spécifier la collection
DBCollection coll= dbs.getCollection("cube");
DBCursor cursor = coll.find();
while(cursor.hasNext()) {
int i=1;
System.out.println(cursor.next());
i++;
}
System.out.println("********************************************* ");
// Select Where region = afriqua
BasicDBObject query = new BasicDBObject("Region", "Afriqua");
DBCursor curs = coll.find(query);
try {
while(cursor.hasNext()) {
int i=1;
DBObject obj = curs.next();
System.out.println(obj.get("Region") + " => " + obj.get("info"));
i++;
}
} finally {
curs.close();
}
}
}

mongodb lookup function returns an empty array result

I have two mongodb collections employee and department as follows
employee collection:
{
"_id" : ObjectId("58c4a35ac2e604024321788e"),
"id_employee" : 19,
"employee_name" : "Lene Vestergaard Hau",
"employee_address" : "Allerton",
"hours" : 279,
"id_department" : 1,
"projects" : [
285,
453,
499,
804,
956
],
"Children" : [
{
"id_child" : 38,
"child_name" : "Caroline Herschel"
}
]
}
department collection:
{
"_id" : ObjectId("58c49c48c2e669d6555aa5a7"),
"id_department" : 1,
"department_name" : "dept1",
"projects" : [
{
"id_project" : 285,
"project_name" : "1project 285",
"duration" : "211"
},
{
"id_project" : 453,
"project_name" : "1project453",
"duration" : "214"
},
{
"id_project" : 499,
"project_name" : "1project499",
"duration" : "224"
},
{
"id_project" : 804,
"project_name" : "1project804",
"duration" : "217"
}
{
"id_project" : 956,
"project_name" : "1project956",
"duration" : "217"
}
]
I am trying to perform a lookup function to get all the details about the
projects for the employee. The java code I am using :
coll.aggregate(Arrays.asList(
Aggregates.match(Filters.eq("id_employee",19)),
Aggregates.unwind("$projects"),
Aggregates.lookup("department", "projects", "projects.id_project", "lookupData")
)).forEach(printBlock);
}
the code above return lookupData as an empty list. Can any one help please?

Elasticsearch aggregation return always empty buckets [] (elasticsearch version 2.4.1)

I have the following code:
final String index = ElasticSearchUtils.getIndexNameForExecution(queryId);
SearchRequestBuilder query = client.prepareSearch(index);
query.setTypes(indexType.toString());
query.addAggregation(terms("errors").field("code").size(NUMBER_OF_HITS).order(Terms.Order.count(false)));
int pageStart = getFrom(page) * size;
SearchResponse response = query.setFrom(pageStart).setSize(getPageSize(size)).execute().actionGet();
return response.toString();
and part of response is:
{
"took" : 78,
"timed_out" : false,
"_shards" : {
"total" : 2,
"successful" : 2,
"failed" : 0
},
"hits" : {
"total" : 2,
"max_score" : 1.0,
"hits" : [ {
"_index" : "index_587e1e34e4b040c63c49137f",
"_type" : "ERROR",
"_id" : "AVmspgsKa7ZIkZu1p32G",
"_score" : 1.0,
"_source" : {
"agent_id" : "{8668b249-9443-e611-87c6-005056aa41d1}",
"_v" : "1",
"host" : "RHEL65-X86-DEMO",
"created_at" : "2017-01-17T13:37:58.496Z",
"qid" : "587e1e34e4b040c63c49137f",
"errors" : [ {
"code" : 769,
"module" : "FileHashing",
"function" : "FindFiles"
} ]
}
}, {
"_index" : "index_587e1e34e4b040c63c49137f",
"_type" : "ERROR",
"_id" : "AVmspgsKa7ZIkZu1p32H",
"_score" : 1.0,
"_source" : {
"agent_id" : "{7238f027-fbfc-47cf-85b0-c69838e26a2a}",
"_v" : "1",
"host" : "W8-X64-DEMO",
"created_at" : "2017-01-17T13:37:58.501Z",
"qid" : "587e1e34e4b040c63c49137f",
"errors" : [ {
"code" : 769,
"module" : "FileHashing",
"function" : "FindFiles"
} ]
}
} ]
},
"aggregations" : {
"errors" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [ ]
}
}
}
And the result of search execution is:
As you can see the buckets is empty [], aggregation is not working, but any exception is throwing. This is occurring with elasticsearch 2.4.1, the same code is working with elasticsearch 1.4.1
You simply need to fix this line
query.addAggregation(terms("errors").field("errors.code").size(NUMBER_OF_HITS).order(Terms.Order.count(false)));
^
|
add this

Would this situation be a mongodb server's bug?

Today I try to $set a DBRef with $db to collection.
But server say: "not okForStorage" , so operation is failed.
ps. my mongod version is 2.2
{
"ts" : ISODate("2013-01-16T14:05:42.814Z"),
"op" : "update",
"ns" : "mydb.coll1",
"query" : {
"_id" : NumberLong("928686353793211381")
},
"updateobj" : {
"$set" : {
"ref" : {
"$db" : "db2",
"$ref" : "coll2",
"$id" : NumberLong("928686353793211381")
}
}
},
"nscanned" : 1,
"keyUpdates" : 0,
"numYield" : 0,
"lockStats" : {
"timeLockedMicros" : {
"r" : NumberLong(0),
"w" : NumberLong(200)
},
"timeAcquiringMicros" : {
"r" : NumberLong(0),
"w" : NumberLong(5)
}
},
"exception" : "not okForStorage",
"exceptionCode" : 12527,
"millis" : 0,
"client" : "10.168.89.9",
"user" : ""
}
According to the docs, the order of the fields in the DBRef matters; so you'd need to reorder your ref object as:
"ref" : {
"$ref" : "coll2",
"$id" : NumberLong("928686353793211381"),
"$db" : "db2"
}

Categories

Resources