Fetching the values from mongodb collection using java - java

These are 2 different collections in a database.I am not able to figure out how to dynamically fetch the values from the collections using java .
I want to fetch the values through java program but without using the
hardcoded values like "VerifyEmail.LicenseKey" & "wsf:status.arg0.age" as mentioned above in the java code.Is there a way to fetch the values without hardcoding in java.
Collection 1:
{
"_id" : ObjectId("583567ac6c85e71adc1f8bae"),
"wsf:status" : {
"arg0" : {
"name" : "James",
"phonenum" : NumberLong(9848222338),
"age" : 18
"status" : "N"
}
},
}
Query 1:
Here I am using the hardcoded values to fetch the desired result from the collection 1.
db.xmlcoll1.find({"wsf:status.arg0.age":18})
Collection 2:
{
"_id" : ObjectId("582446686c85e73a70696666"),
"VerifyEmail" : {
"xmlns" : "http://ws.cdyne.com/",
"email" : "james#yahoo.com",
"LicenseKey" : 123
} }
Query 2:
Here I am using the hardcoded value of the element "VerifyEmail"
to fetch the values.
db.xmlcoll.find({"VerifyEmail.LicenseKey":123});

You can try to use Morphia if performance is not critical for you. And use such constructions for queries:
underpaid = datastore.createQuery(Employee.class)
.field("age").lessThanOrEq(18)
.asList();

Related

How to use $wind for adding list value in mongodb

I have my mongodb document structure as shown below:
{
"_id" : NumberLong(366),
"_class" : "com.cts.adpart.domain.DBData",
"curatorList" : [
{
"_id" : NumberLong(0),
"userBI" : "2",
}
]
}
I have to sum the userBI values from all documents in a collection and display the result
I have tried the below query but it is always returning 0
db.collection.aggregate[ {$unwind: "$curatorList"},{$group : {_id : null , sum: {$sum:"$curatorList.userBI"} } } ]
Can anyone help me with the solution?
The field value is string "2", change it to 2 and your query is going to work.

spring data returning map from mongodb aggregation results

Is there any way that i can get a map as a result of a mongodb query using some spring data CrudRepository ?
Here is my method which is returning a list of objects.
Query(value = "db.tweet_replies.aggregate([ {$match: { 'in_reply_parent_tweet_ID' : {$exists : true}}}, {$group: { _id: '$in_reply_parent_tweet_ID', maxDate: {$max : { $cond: [ {$gt : ['authorization_date_time','$user_reply.authorization_date_time']},'$authorization_date_time','$user_reply.authorization_date_time']}}}}])")
List<fReply> findByInReplyParentPostID(final String inReplyParentPostID);
for example it gives me this result.
{ "_id" : "638251888450756608", "maxDate" : NumberLong("1441006865000") }
{ "_id" : "637192023661895680", "maxDate" : NumberLong("1440760528000") }
i want to store this result a typed map instead of object list. Any idea ? . Thanks in advance :)
It seems there's no simple way to do this, see this question : Can JPA return results as a map?
Maybe you could create a service on top of your CrudRepository in which you translate from the List you have to the Map you wish ?

Effective use of Array field in Mongo Collection

We are using Mongo DB in our application and in our collection we are storing array as field. eg:
{
"_id" : ObjectId("54ef67573848ec32b156b053"),
"articleId" : "46384262",
"host" : "example.com",
"url" : "http://example.com/articleshow/46384262.cms",
"publishTime" : NumberLong("1424954100000"),
"tags" : [
"wind power",
"mytrah",
"make in india",
"government",
"andhra pradesh"
],
"catIds" : [
"2147477890",
"13352306",
"13358350",
"13358361"
]
}
Now my situation is need to create index on tags and catIds array as they are search field.
But creating an index on array field increases the size of indexes tremendously.
Could you please suggest a better way of achiving this.
You can restructure your collection in this way. Now you will have 3 collections:
Coll1, documents look like this:
{
"_id" : ObjectId("54ef67573848ec32b156b053"),
"articleId" : "46384262",
... your other stuff
}
Tags, documents look like this:
{
'_id': 1,
'name': 'wind power'
}
{
'_id': 2,
'name': 'mytrash'
}
....
and a collection that links coll1 to tags:
{
"collID" : ObjectId("54ef67573848ec32b156b053"),
"tagID": 1
}
{
"collID" : ObjectId("54ef67573848ec32b156b053"),
"tagID": 2
}
Mongo does not have joins, so you need to do joins on the application layer. And it will take you 3 mongo queries. The size of indexes should be smaller, but test it before making significant changes.

Morphia Query on Array of Subdocuments using elem

I have the following document structure in mongodb collection "Contact". There is an array of subdocuments called "numbers":
{
"name" : "Bill",
"numbers" : [
{
"type" : "home",
"number" : "01234",
},
{
"type" : "business",
"number" : "99099"
},
{
"type" : "fax",
"number" : "77777"
}
]
}
When I want to query only for "home" and "business" numbers, I can do something like this in mongodb-shell:
db.Contact.find({ numbers: { $elemMatch: {
type : { $in : ["home", "business"]},
number: { $regex : "^012" }
}}});
But how to do this in morphia? Is there any way?
I understand "$elemMatch" is supported in morphia. So I could do something like:
query.filter("numbers elem", ???);
But how exactly do I add a combined query for the subdocument?
It is too late, but maybe others can find it handy.
I found that solution https://groups.google.com/forum/#!topic/morphia/FlEjBoSqkhg
query.filter("numbers elem",
BasicDBObjectBuilder.start()
.push("type").add("$in", new String[]{"home", "business"}).pop()
.push("number").add("$regex", "^012").pop().get());
Instead of using morphia, consider using jongo. It lets you query MongoDB as you were using MongoDB shell. Furthermore, it will give you more freedom when mapping your array elements. Here is how your example will look with jongo:
contacts_collection.find("{numbers : {$elemMatch: {
type: {$in :#},
number: {$regex: #}
}
}
}",
new String[]{"home", "business"}, "^012")
.as(Contact.class);
Note that, if you only need a single number object (or multiple) from the array you can use a custom result mapper/handler. You just have to substitute .as(Contact.class) with :
.map(new ResultHandler<Number>() {...})
For a full example take a look at my blog post or at my GitHub repository

How to add where clause in elasticsearch

I am very new to elasticsearch. I have an elastic search query which returns all users present in database based on keyword but here I need to get only the users whose active status is true but now I am getting all list of users.
I have built a search query like
{
"from" : 0,
"size" : 30,
"query" : {
"query_string" : {
"query" : "*jhon*",
"default_field" : "_all"
}
},
"sort" : [
{
"id" : {
"order" : "desc"
}
}
]
}
I am using a query like *jhon*, but I need to get result like users with name jhon and his active status should be true, so I have tried *"+jhon+"\*"#activated~true" but I am not getting the desired result.
I don't know what I am doing wrong.
It's best to add a filter to your query. Filters are faster since they don't involve any scoring and are cached. There are different filters that you can use, the elasticsearch query DSL is really flexible. The kind of filters depends on the way you indexed data, which depends on your data. I'll assume the easiest possbile solution: a term filter. Have a look at the following example.
{
"from" : 0,
"size" : 30,
"query" : {
"query_string" : {
"query" : "*jhon*",
"default_field" : "_all"
}
},
"filter" : {
"term" : {
"activated" : "true"
}
},
"sort" : [
{
"id" : {
"order" : "desc"
}
}
]
}
Beware that there are different ways to apply filters when searching. In my example I applied a top level filter, which will only be applied to the search results, and not to the facets. If you want it to be applied to the facets too, you should have a look at the filtered query; instead of adding a filter you would wrap your current query into new filtered query, which can also contain the same term filter.

Categories

Resources