I have some documents in my MongoDB database.
Looks like this:
{ "_id" : { "$oid" : "5598d61b0cfb246b90daa3f7" }, "name" : "Sarah", "uuid" : "488f69e9-8070-40f0-8c0a-b5d0bd53bdfe", "createdDate" : { "$date" : 1436079643735 }, "istested" : false }
{ "_id" : { "$oid" : "5598d6260cfb2461d4ad4f98" }, "name" : "Omah", "uuid" : "93e572c0-8acd-4397-8487-4d458bbafa8d", "createdDate" : { "$date" : 1436079654217 }, "istested" : false }
{ "_id" : { "$oid" : "5598d6300cfb246bace63cef" }, "name" : "Secret", "uuid" : "60e1413e-49e3-4315-a970-7111d55fe8d1", "createdDate" : { "$date" : 1436079664902 }, "istested" : false }
Now I wan to get the name
where uuid = 93e572c0-8acd-4397-8487-4d458bbafa8d (Omah)
How do I do this? (Using com.mongodb.async)
To get the name where uuid = 93e572c0-8acd-4397-8487-4d458bbafa8d, use the find() method to query the collection, create a filter to pass to the find() method to get a subset of the documents in your collection, use the projection parameter in the Projections helper class for the find operation to limit the fields returned, and then call the first() method on the find() operation to return the first document or null rather than a cursor. For example,
import static com.mongodb.client.model.Projections.*;
import static com.mongodb.client.model.Filters.*;
Block<Document> printDocument = new Block<Document>() {
#Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
collection.find(eq("uuid", "93e572c0-8acd-4397-8487-4d458bbafa8d"))
.projection(fields(include("name"), excludeId()))
.first(printDocument);
will print the document:
{ "name" : "Omah" }
Related
I'm currently learning about Spring Boot and am undertaking a project where users can make posts, view those posts, etc.
A user's post(s) can be viewed via http://localhost:8080/users/{user_id}/posts and http://localhost:8080/users/{user_id}/posts/{post_id}
As a result I have the following UserPostController
#RestController
#RequestMapping("/users")
public class UserPostController {
#Autowired
private UserPostService postService;
#GetMapping("/{user_id}/posts")
public List<Post> retrieveUserPosts(#PathVariable int user_id) {
return postService.retrieveUserPostList(user_id);
}
#GetMapping("/{user_id}/posts/{post_id}")
public EntityModel<Post> retrieveUserPost(#PathVariable int user_id, #PathVariable int post_id) {
return postService.retrieveUserPost(user_id, post_id);
}
#PostMapping("/{user_id}/posts")
public ResponseEntity<Object> createUserPost(#PathVariable int user_id, #Valid #RequestBody Post post) {
return postService.saveUserPost(user_id, post);
}
}
Every request to the links work correctly. For example a GET request to http://localhost:8080/users/1/posts returns [{"id":1,"description":"This is a post"},{"id":2,"description":"This is another post"}], which is the expected action.
However, for some reason I am able to visit http://localhost:8080/posts which then returns a list of all posts:
{
"_embedded" : {
"posts" : [ {
"description" : "This is a post",
"_links" : {
"self" : {
"href" : "http://localhost:8080/posts/1"
},
"post" : {
"href" : "http://localhost:8080/posts/1"
},
"user" : {
"href" : "http://localhost:8080/posts/1/user"
}
}
}, {
"description" : "This another post",
"_links" : {
"self" : {
"href" : "http://localhost:8080/posts/2"
},
"post" : {
"href" : "http://localhost:8080/posts/2"
},
"user" : {
"href" : "http://localhost:8080/posts/2/user"
}
}
}, {
"description" : "This is yet another post",
"_links" : {
"self" : {
"href" : "http://localhost:8080/posts/3"
},
"post" : {
"href" : "http://localhost:8080/posts/3"
},
"user" : {
"href" : "http://localhost:8080/posts/3/user"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/posts"
},
"profile" : {
"href" : "http://localhost:8080/profile/posts"
}
},
"page" : {
"size" : 20,
"totalElements" : 3,
"totalPages" : 1,
"number" : 0
}
}
Through HATEOAS I am able to also see available links of the format http://localhost:8080/posts/{user_id}/user which I have also not created methods for, but they still exist.
Is there a reason why these unwanted routes exist? If so how do I change this?
Thank you :)
Please find my mapping query below for the filename field.
PUT /articles
{
"settings" : {
"analysis" : {
"analyzer" : {
"filename_search" : {
"tokenizer" : "filename",
"filter" : ["lowercase"]
},
"filename_index" : {
"tokenizer" : "filename",
"filter" : ["lowercase","edge_ngram"]
}
},
"tokenizer" : {
"filename" : {
"pattern" : "[^\\p{L}\\d]+",
"type" : "pattern"
}
},
"filter" : {
"edge_ngram" : {
"side" : "front",
"max_gram" : 50,
"min_gram" : 1,
"type" : "edgeNGram"
}
}
}
},
"mappings" : {
"doc" : {
"properties" : {
"filename" : {
"type" : "text",
"search_analyzer" : "filename_search",
"analyzer" : "filename_index"
}
}
}
}
}
If am trying to query series1333372 doc623258 and am expecting karthik_series1333372_oracle_page_doc623258_v1_en-EU.pdf. But it's giving all the files which is having series1333372, not even checking for doc623258.
Please find my query below
get articles/_search
{
"query" : {
"match" : {
"filename" : "series1333372 doc623258"
}
}
}
I am inserting the following sample documents for testing from Kibana
POST articles/doc/1
{
"filename" : "karthik_series1333372_oracle_page_doc623258_v1_en-EU.pdf"
}
POST articles/doc/2
{
"filename" : "karthik_series1333372_sun_page_doc658_v1_en-EU.pdf"
}
POST articles/doc/3
{
"filename" : "series1333372_oracle_page_doc623_v1_en-US.pdf"
}
POST articles/doc/4
{
"filename" : "Engineering series1333372 valve_page doc6232 v1_en-US.pdf"
}
POST articles/doc/5
{
"filename" : "Machines_series1333372_page_doc62258_v1_en-US.pdf"
}
POST articles/doc/6
{
"filename" : "AIX series1333372 IBM page doc62358 v1_en-EU.pdf"
}
The default operator of match is OR. If you want all your terms to be present change it like this
GET articles/_search
{
"query" : {
"match" : {
"filename" : {
"query": "series1333372 doc623258",
"operator" : "and"
}
}
}
}
This is how the json looks like
"Node" : {
"1-5-2018" : {
"10001" : {
"centre" : "centre_1",
"name" : "name_1",
"paidAmt" : "25000"
},
"10002" : {
"centre" : "centre_2",
"name" : "name_2",
"paidAmt" : "25000"
},
"10003" : {
"centre" : "centre_3",
"name" : "name_3",
"paidAmt" : "10000"
}
},
"2-5-2018 : {
"10004" : {
"centre" : "centre_4",
"name" : "name_4",
"paidAmt" : "20000"
}
}
I want to retrieve the values(centre, name and paidAmt) inside the given dates
I've tried using this particular query but it always shows data does not exist
Query query = databaseReference1.orderByKey().startAt(fromDate.getText().toString()).endAt(toDate.getText().toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Log.d(TAG, "Data exists within dates");
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Log.d(TAG , "Data are " + ds.getValue().toString());
}
}
else {
Log.d(TAG, "Data does not exist within dates");
}
}
Please let me know if it's possible to retrieve all the data within dates. In future i'm planning to add multiple data inside different dates and want to retrieve them based on requirement. Maybe monthly or weekly.
You are using timestamp instead of a date it may look like this.
"Node" : {
"1525188857" : {
"10001" : {
"centre" : "centre_1",
"name" : "name_1",
"paidAmt" : "25000"
},
"10002" : {
"centre" : "centre_2",
"name" : "name_2",
"paidAmt" : "25000"
},
"10003" : {
"centre" : "centre_3",
"name" : "name_3",
"paidAmt" : "10000"
}
},
"1525188873" : {
"10004" : {
"centre" : "centre_4",
"name" : "name_4",
"paidAmt" : "20000"
}
}
I'm getting json object on my mongodb with virustotal API
This is how a json object stored in mongodb object looks like :
{
"_id" : ObjectId("597cd2f871eac714388b2f7f"),
"results" : {
"scans" : {
"Bkav" : {
"detected" : true,
"version" : "1.3.0.8042",
"result" : "W32.HfsAutoB.971A",
"update" : "20160706"
},
"TotalDefense" : {
"detected" : false,
"version" : "37.1.62.1",
"result" : null,
"update" : "20160706"
},
"MicroWorld-eScan" : {
"detected" : true,
"version" : "12.0.250.0",
"result" : "Packer.Expressor.B",
"update" : "20160706"
},
"nProtect" : {
"detected" : true,
"version" : "2016-07-06.01",
"result" : "Packer.Expressor.B",
"update" : "20160706"
},
"ALYac" : {
"detected" : false,
"version" : "1.0.1.9",
"result" : null,
"update" : "20160706"
},
"TrendMicro" : {
"detected" : true,
"version" : "9.740.0.1012",
"result" : "TROJ_GEN.R047C0CAP16",
"update" : "20160706"
},
"McAfee-GW-Edition" : {
"detected" : true,
"version" : "v2015",
"result" : "BehavesLike.Win32.Flyagent.cc",
"update" : "20160706"
},
"Sophos" : {
"detected" : true,
"version" : "4.98.0",
"result" : "W32/Pidgeon-A",
"update" : "20160706"
},
"Cyren" : {
"detected" : true,
"version" : "5.4.16.7",
"result" : "W32/SysVenFak.A.gen!Eldorado",
"update" : "20160706"
},
"Microsoft" : {
"detected" : true,
"version" : "1.1.12902.0",
"result" : "Backdoor:Win32/Delf.SJ",
"update" : "20160706"
},
"AegisLab" : {
"detected" : true,
"version" : "4.2",
"result" : "Backdoor.W32.BlackHole.acx!c",
"update" : "20160706"
},
"Qihoo-360" : {
"detected" : false,
"version" : "1.0.0.1120",
"result" : null,
"update" : "20160706"
}
},
"scan_id" : "2ad6e0aad0b40f152f234787daa4afb87538f3278f5c8f815d53ef46d5eea4ac-1467833095",
"sha1" : "c5dcd5526ac5330ad1e9fad51488718329fdb697",
"resource" : "0a60424e0967b6cfc172dac82e10a2fe",
"response_code" : 1,
"scan_date" : "2016-07-06 19:24:55",
"permalink" : "https://www.virustotal.com/file/2ad6e0aad0b40f152f234787daa4afb87538f3278f5c8f815d53ef46d5eea4ac/analysis/1467833095/",
"verbose_msg" : "Scan finished, information embedded",
"total" : 54,
"positives" : 41,
"sha256" : "2ad6e0aad0b40f152f234787daa4afb87538f3278f5c8f815d53ef46d5eea4ac",
"md5" : "0a60424e0967b6cfc172dac82e10a2fe"
},
"response_code" : 200
}
As you can see the json object is too complicated to just get given value from,
This is what i've tried so far :
MongoClient mongo = new MongoClient("localhost", 27017);
MongoDatabase database1 = mongo.getDatabase(db);
MongoCollection<Document> collection1 = database1.getCollection(col);
try (MongoCursor<Document> cursor = collection1.find().iterator()){
while (cursor.hasNext()){
Document doc = cursor.next();
List list = new ArrayList(doc.values());
System.out.println(list.get(1));
}
}
I was thinking maybe there is a way to map all this json to a java class, the main problem is with the "scans" as there are many different scannors and it isn't optimized to create a java class model to each of them,
My question is how can i store directly my json objects to a java object so as to operate on the results returned.
I am calling your main model as Scan. You can create a POJO (lets call it Scanner) with below attributes:
scannerName, detected, version, result, update;
Scanner.java
private String scannerName;
private String detected;
private String version;
private String result;
private String update;
Scan.java
private String scan_id;
private List<Scanner> = new ArrayList<Scanner>();
private String sha1;
private String resource;
......
........
So your scan model now has a List of scanners.
Using morphia its something like:
#Embedded
private List<Scanner> scanner;
If you are not using any wrapper around the java-driver, just try
private List<BasicDBObject>
You need to create two java classes in order to parse Json of coming from Mongo,Suppose First Class Name "CollectionReceived"
Second Class Name "Result"
In CollectionReceived class you need to declare members
public String _id;
public String response_code;
public Result result;
In Result class you need to declare members
Map<String,Map<String,Map<String,Map<String,Object>>>> results=new HashMap<String,Map<String,Map<String,Map<String,Object>>>>();,
public String scan_id;
public String sha1;
public String resource;
public String response_code;
public String scan_date;
public String permalink;
public String verbose_msg;
public String total;
public String positives;
public String sha256;
public String md5;
and don't forget to use #RestController on your controller, You will parse Json Easily and get all the values you required.
How to get expected output below where OrderProjection uses ItemProjection to render Items using Spring Data REST
GET /orders/1?projection=with_items
Projections :
#Projection(name = "summary", types = Item.class)
public interface ItemProjection {
String getName();
}
#Projection(name = "with_item", types = Order.class)
public interface OrderProjection {
LocalDateTime getOrderedDate();
Status getStatus();
Set<ItemProjection> getItems(); // this is marshalling as Set<Item> (full Item graph)
}
Currently getting as output:
{
"status" : "PAYMENT_EXPECTED",
"orderedDate" : "2014-11-09T11:33:02.823",
"items" : [ {
"name" : "Java Chip",
"quantity" : 1,
"milk" : "SEMI",
"size" : "LARGE",
"price" : {
"currency" : "EUR",
"value" : 4.20
}
} ],
"_links" : {
"self" : {
"href" : "http://localhost:8080/orders/1{?projection}",
"templated" : true
},
"restbucks:items" : {
"href" : "http://localhost:8080/orders/1/items"
},
"curies" : [ {
"href" : "http://localhost:8080/alps/{rel}",
"name" : "restbucks",
"templated" : true
} ]
}
}
Expected Output:
{
"status" : "PAYMENT_EXPECTED",
"orderedDate" : "2014-11-09T11:33:02.823",
"items" : [ {
"name" : "Java Chip"
} ],
"_links" : {
"self" : {
"href" : "http://localhost:8080/orders/1{?projection}",
"templated" : true
},
"restbucks:items" : {
"href" : "http://localhost:8080/orders/1/items"
},
"curies" : [ {
"href" : "http://localhost:8080/alps/{rel}",
"name" : "restbucks",
"templated" : true
} ]
}
}
You're running into DATAREST-394 which has been fixed a few days a go and will be making it into 2.2.2 and 2.3 RC1. It's already available in the snapshots for said versions, feel free to give them a spin.