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
Related
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
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.
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);
I've setup a simple grails app looking at a mongodb.
My domain object looks like this:
class GoogleSearch {
String _id;
String id;
String query;
String site;
Object results;
Date date;
static mapping = {
table 'google_searches'
}
static constraints = {
}
}
However when I run the grails app up, it keeps reading/writing to a table named "googleSearch"
Does anyone know how I can override this default naming? Is it a gorm/mongodb thing?
Cheers
Basics of MongoDB. There is no concept of table. It is always collections. :)
Refer mapping as collection 'google_searches'.
For more details you can refer Grails MongoDB plugin.
I need to iterate through all of the collections in my MongoDB database and get the time when each of the collections was created (I understand that I could get the timestamp of each object in the collection, but I would rather not go that route if a simpler/faster method exists).
This should give you an idea of what I'm trying to do:
MongoDatabase _database;
// code elided
var result = _database.GetAllCollectionNames().Select(collectionName =>
{
_database.GetCollection( collectionName ) //.{GetCreatedDate())
});
As far as I know, MongoDB doesn't keep track of collection creation dates. However, it's really easy to do this yourself. Add a simple method, something like this, and use it whenever you create a new collection:
public static void CreateCollectionWithMetadata(string collectionName)
{
var result = _db.CreateCollection(collectionName);
if (result.Ok)
{
var collectionMetadata = _db.GetCollection("collectionMetadata");
collectionMetadata.Insert(new { Id = collectionName, Created = DateTime.Now });
}
}
Then whenever you need the information just query the collectionMetadata collection. Or, if you want to use an extension method like in your example, do something like this:
public static DateTime GetCreatedDate(this MongoCollection collection)
{
var collectionMetadata = _db.GetCollection("collectionMetadata");
var metadata = collectionMetadata.FindOneById(collection.Name);
var created = metadata["Created"].AsDateTime;
return created;
}
The "creation date" is not part of the collection's metadata. A collection does not "know" when it was created. Some indexes have an ObjectId() which implies a timestamp, but this is not consistent and not reliable.
Therefore, I don't believe this can be done.
Like Mr. Gates VP say, there is no way using the metadata... but you can get the oldest document in the collection and get it from the _id.
Moreover, you can insert an "empty" document in the collection for that purpose without recurring to maintain another collection.
And it's very easy get the oldest document:
old = db.collection.find({}, {_id}).sort({_id: 1}).limit(1)
dat = old._id.getTimestamp()
By default, all collection has an index over _id field, making the find efficient.
(I using MongoDb 3.6)
Seems like it's some necroposting but anyway: I tried to find an answer and got it:
Checked it in Mongo shell, don't know how to use in C#:
// db.payload_metadata.find().limit(1)
ObjectId("60379be2bec7a3c17e6b662b").getTimestamp()
ISODate("2021-02-25T12:45:22Z")