Read element from nested map by key. mongodb spring data - mongodb

there is the following structure
#Id
private String beaconMac;
private SortedMap<LocalDate, Map<Integer, HistoryData>> history;
How i can read internal value from 'history' map by key? how to make a right query? or meybe in spring data there is a blank like
NestedObject repo.findNestedObjectByDate(LocalDate date);
Very grateful!

If I understand correctly, you want something like:
db.collection.find({
beaconMac: "C145109D4D5C"
},
{
"history.2020-20-02": 1,
beaconMac: 1
})
The first part is the match, in which you choose what documents you want. The second is the projection, in which you format the fields you want to see.
As You can see on this playground

Related

Spring MongoRepository not returning id field of nested objects [duplicate]

I have a document with an array field with
"chapters": [
{ "id" : "14031871223912313", ...}
...
]
I would like to query return the id's with Spring Data's MongoTemplate using the following:
class Chapter {
private String id;
public String getId() {
return id;
}
}
This way the id is not populated. I have tried using the different mapping options with #Field described here http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping.conventions.id-field
What am I doing wrong? I know I can always to back to mongo java driver, but I thought this should work.
Thanks in advance for any help.
Found a solution. It is populated via:
#Field("id")
private String chaperId
In MongoDB id's are _id, and every document in mongo has an _id. From the document you linked to, Spring will map #Field String id to mongo's _id field. You probably want to use a #Field('id') String id field mapping to indicate that the field you want is id not _id.

How to pass variable between two queries in MongoDB?

I want to put the query result from one collection in a variable and use it as input for query in another collection. The queries look like this as follows:
Query 1:
var ID=db.User.findOne({Name:"Ivan"}, {ID: 1});
db.Artists.find({"Listeners.ID":ID});
Query 2:
var Friends=db.Users.find({Friends:x});
//Users.Friends is an array of interger identifier for User
db. Artists.find({"Listeners.ID":{$in:Friends}});
But they all don't work. How to write the right one?
The query db.User.findOne({Name:"Ivan"}, {ID: 1}); does not return a single value, it returns the document, reduced to the field you requested. What you get is an object, with two fields: _id (because you didn't explicitly exclude it) and ID (when it exists in the document). Your var ID looks like this:
{
_id:ObjectId(<long hex string>),
ID:<value>
}
So when you want to query by the ID value, you need to specify it:
db.Artists.find({"Listeners.ID":ID.ID});
Regarding your second query: when you use find instead of findOne you get a cursor object which can then be used to retrieve the individual documents using cursor.next() or cursor.toArray().

updating a multi-embedded data in mongodb

I want to insert into an array-list in an embedded data. I tried several ways but couldn't make it out. My data structure is something like this. The code given here is just a dummy reference to my original data structure
Class X{
Integer _id;
Arraylist<Y> objY;
}
Class Y{
Integer _id;
Arraylist<Z> objZ;
}
Class Z{
Integer _id;
String value;
String oldValue
}
I want to insert a new data into objZ
I know the id value of Class X an Y.
I am using Spring mongotemplate.
Does Spring Mongo Template Supports this?
Can someone help me out through this.
Thanks in advance.
I got it hope it might help someone out here, Use aggregetion to do this.
Query searchUserQuery = new Query((Criteria.where("_id").is("542264c8e4b098972a1cf60c").and("leads._id").is("2")));// _id is the id of class X
AggregationOperation match = Aggregation.match(searchUserQuery );
AggregationOperation group = Aggregation.group("objY");
Aggregation aggregation = Aggregation.newAggregation(Aggregation.unwind("objY"),match, group);
List<objY> asd=mongoOperation.aggregate(aggregation, "Name_of_ur_collection", B.class).getMappedResults();
ArrayList<Z> s=asd.get(0).getObjZ();
s.add("New Data to be added");
mongoOperation.updateFirst(searchUserQuery, Update.update("objY.$.objZ", s), X.class);
This will insert your array list in class Y.
Thanks

query based on matching elements in DBRef list for mongodb using spring-data-mongodb

I am pretty new to mongodb. I am using spring-data-mongodb for my queries from java. Please guide me if this is achievable.
Say I have two objects "Car" and "User" as following, where car has list of users,
Class Car {
#Id
String id;
String model;
#DBRef
List<User> users;
#DBRef
Company company;
}
Class User {
#Id
String id;
String name;
}
I want to find all cars for a user, (find all cars where car.users has given user)
Is it possible to achieve using spring-data-mongodb?
It's pretty easy if there was only one DBRef element, eg, for company I can write a query like this,
new Query(Criteria.where("company.$id").is(new ObjectId(companyId)))
But, how to achieve this if there is a list of elements referenced as DBRef??
Thanks for help.
Querying for one element on an array is exactly like query for a field equality. You could read the MongoDB documentation here. So your query will be:
new Query(Criteria.where("users.$id").is(new ObjectId(userId)))
in repository interface type this query on the method:
#Query("{'company' :{'$ref' : 'company' , '$id' : ?0}}")
Company find(String companyId);

MongoDB C# offic. List<BsonObject> query issue and always olds values?

I have not clearly issue during query using two criterials like Id and Other. I use a Repository storing some data like id,iso,value. I have created an index("_id","Iso") to performs queries but queries are only returning my cursor if i use only one criterial like _id, but is returning nothing if a use two (_id, Iso) (commented code).
Are the index affecting the response or the query method are failing?
use :v1.6.5 and C# official.
Sample.
//Getting Data
public List<BsonObject> Get_object(string ID, string Iso)
{
using (var helper = BsonHelper.Create())
{
//helper.Db.Repository.EnsureIndex("_Id","Iso");
var query = Query.EQ("_Id", ID);
//if (!String.IsNullOrEmpty(Iso))
// query = Query.And(query, Query.EQ("Iso", Iso));
var cursor = helper.Db.Repository.FindAs<BsonObject>(query);
return cursor.ToList();
}
}
Data:
{
"_id": "2345019",
"Iso": "UK",
"Data": "Some data"
}
After that I have Updated my data using Update.Set() methods. I can see the changed data using MongoView. The new data are correct but the query is always returning the sames olds values. To see these values i use a page that can eventually cached, but if add a timestamp at end are not changing anything, page is always returning the same olds data. Your comments are welcome, thanks.
I do not recall offhand how the C# driver creates indexes, but the shell command for creating an index is like this:
db.things.ensureIndex({j:1});
Notice the '1' which is like saying 'true'.
In your code, you have:
helper.Db.Repository.EnsureIndex("_Id","Iso");
Perhaps it should be:
helper.Db.Repository.EnsureIndex("_Id", 1);
helper.Db.Repository.EnsureIndex("Iso", 1);
It could also be related to the fact that you are creating indexes on "_Id" and the actual id field is called "_id" ... MongoDB is case sensitive.
Have a quick look through the index documentation: http://www.mongodb.org/display/DOCS/Indexes