Spring Data - Query by List - mongodb

Is it possible to make a List Query that results in one value? The following does not work. The result is null. The combination of optionValues will result in one variant.
Here is my Data:
OptionValues
[
{
"id" : "5cc248eeaa4a4f7b35454079",
"optionType" : {
"id" : "5cc2301ab2c4cea611ceb13d",
"name" : "size",
"title" : "Size"
},
"value" : "S"
}
]
Variant
{
"id" : "5cc24361b2c4cea611cee8c9,
"optionValues" : [
{
"id" : "5cc248eeaa4a4f7b35454079",
"optionType" : {
"id" : "5cc2301ab2c4cea611ceb13d",
"name" : "size",
"title" : "Size"
},
"value" : "S"
}
],
"price" : 10.99
}
Variant Model
#Data
#Document
public class Variant extends StoreEntity {
#Id
private String id;
#DBRef
private List<OptionValue> optionValues;
...
}
OptionValues Model
#Data
#Document
public class OptionValue {
#Id
private String id;
#DBRef
private OptionType optionType;
private String value;
}
OptionType Model
#Data
#Document
public class OptionValue {
#Id
private String id;
private String name;
private String title;
}
Variant Repository
Variant findByOptionValues(List<OptionValue> optionValues);

Variant findByOptionValuesIn(List optionValues);

Related

Mongodb PojoCodec Found property not present in the ClassModel: id

Be me, perform aggregate query on MongoDb:
db.Rubrica.aggregate([
{$match: {"fiscalCode": "asfjhsdfhgsdfugsdf"}},
{$project: {
"_id":0,
"contactsHeaders":"$contacts.header",
}}
]);
Get the result:
{
"contactsHeaders" : [
{
"id" : "7b47c1637cde49d182b96bcc33d21d0d",
"alias" : "VOL LISTA",
"type" : "L"
},
{
"id" : "ab31c06ecce244bea4ab5b45b89f4fdc",
"alias" : "VOL FEDRO",
"type" : "S"
}
]
}
Now in Java i try to deserialize the Document in:
public class ListOfHeadersWrapper implements Serializable {
List<Header> contactsHeaders;
....
....
public class Header implements Serializable {
private String id;
private String alias;
private TypeEnum type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
....
....
What I get is:
{
"contacts": [
{
"id": null,
"alias": "VOL LISTA",
"type": "L"
},
{
"id": null,
"alias": "VOL FEDRO",
"type": "S"
}
]
}
id is always null. Logs says Found property not present in the ClassModel: id.
If I deserialize the thing manually with Jackson:
(new ObjectMapper()).readValue(res.toJson(), ListOfHeadersWrapper.class).toString()
I get the correct result:
ListOfHeadersWrapper{contactsHeaders=[Header{id='7b47c1637cde49d182b96bcc33d21d0d', alias='VOL
WHY????
Adding #BsonProperty("id") does the trick:
public class Header implements Serializable {
#BsonProperty("id")
private String id;
...
...
This I think only happens for CosmosDb when used with MongoApi.

Filtering on a Mongo DB capped Collection using Flux

I have defined my capped collection as below.
#Document("#{#environment.getProperty('customProperties.cappedCollection')}")
#Data
#NoArgsConstructor
#Builder
#AllArgsConstructor
public class ActiveRideCapped {
#Id
private String id;
private String riderId;
private GeoJsonPoint location;
}
I am re-creating this collection at application startup using below code.
#Autowired
MongoOperations mongoOperations;
#PostConstruct
public void createCappedCollection() {
mongoOperations.dropCollection(ActiveRideCapped.class);
mongoOperations.createCollection(ActiveRideCapped.class, CollectionOptions.empty().maxDocuments(20).size(50000).capped());
}
The collection in DB looks like below.
{
"_id" : ObjectId("6037656d2f88af2124ba0d8c"),
"riderId" : "1",
"location" : {
"type" : "Point",
"coordinates" : [
0.1223,
2.2145
]
},
},
{
"_id" : ObjectId("603765532f88af2124ba0d8b"),
"riderId" : "2",
"location" : {
"type" : "Point",
"coordinates" : [
0.5468,
2.7856
]
}
}
I have written a capped repository as below
public interface ActiveRideCappedRepository extends ReactiveMongoRepository<ActiveRideCapped, String> {
#Tailable
Flux<ActiveRideCapped> findActiveRideCappedBy();
}
and I have written below code to create a stream of filtered records.
#Override
public Flux<ActiveRideCapped> getRiderLocationStream(String riderId) {
return activeRideCappedRepository.findActiveRideCappedBy().filter(p -> p.getRiderId()!=riderId);
}
My requirement is, I should get filtered stream based on the riderId I am passing. So if I pass riderId=1 then I should get flux of all records where riderId!=1. But the filtering isn't working! I am getting all the records present in capped collection.
What am I doing wrong here?

Spring Boot and Mongo - how to query by nested property

I have the following problem - how to query by nested property with #Query?
My Product class (document in Mongo):
#Document(collection = "products")
public class Product {
#Id
private String id;
#DBRef
private ProductProperties properties;
How does it look in Mongo:
{
"_id" : ObjectId("5d5e78d20e8e3d0006079a84"),
"companyId" : "1234",
"properties" : {
"$ref" : "properties",
"$id" : ObjectId("5df8dd2331ea7b4a9384335b")
},
"calendar" : [
{
"startDate" : ISODate("2019-09-04T22:00:00.000Z"),
"endDate" : ISODate("2019-09-09T22:00:00.000Z")
}
],
"_class" : "org.abc.def"
}
ProductProperties class (document in Mongo):
#Document(collection = "product_properties")
public class ProductProperties {
#Id
private String id;
(...)
How does it look in Mongo:
{
"_id" : ObjectId("5df8dd2331ea7b4a9384335b"),
"brand" : "offer Brand_1",
"model" : "offer model_1",
"modelNumber" : "offer model number_1",
"size" : {
...
}
My Spring repository:
public interface ProductRepository extends MongoRepository<Product, String> {
#Query("{'properties.id': ?0 }")
List<Product> findByPropertiesId(String propertiesId);
I've tried also:
List<Product> findByProperties_id(String propertiesId)
or
#Query("{'properties.$id': ?0 }")
List<Product> findByPropertiesId(ObjectId propertiesId);
but WITHOUT success. DO you know what's wrong?
When I invoke:
public List<Product> findProductsByPropertiesId(String properties) {
if (properties == null) {
throw new IllegalArgumentException("onFind: propertiesId should not be null.");
}
return productRepository.findByProperties_Id(properties);
}
I get empty list:(
Maybe there is impossible to do that via Query?
#Query("{'properties.$id': ?0 }")
List<Product> findByPropertiesId(ObjectId propertiesId);
public List<Product> findProductsByPropertiesId(String properties) {
if (properties == null) {
throw new IllegalArgumentException("onFind: propertiesId should not be null.");
}
return productRepository.findByPropertiesId(new ObjectId(properties));
}

Morphia mapping with my JAVA Class

I am trying to do a simple findOne() using morphia. my code goes as follows:
public static void main(String[] args)
{
MongoClient client = new MongoClient();
Morphia morphia = new Morphia();
morphia.map(Restaurant_M.class);
Datastore ds = morphia.createDatastore(client, "test");
System.out.println(ds.find(Restaurant_M.class).get());
client.close();
}
I get a null printed out. I am unable to find whats going wrong. Can someone point me in the right direction? Thanks.
EDIT
Collection format
{
"_id" : ObjectId("572eb5df1d739cc73c21f953"),
"address" : {
"building" : "469",
"coord" : [
-73.961704,
40.662942
],
"street" : "Flatbush Avenue",
"zipcode" : "11225"
},
"borough" : "Brooklyn",
"cuisine" : "Hamburgers",
"grades" : [
{
"date" : ISODate("2014-12-30T00:00:00Z"),
"grade" : "A",
"score" : 8
},
{
"date" : ISODate("2014-07-01T00:00:00Z"),
"grade" : "B",
"score" : 23
},
{
"date" : ISODate("2013-04-30T00:00:00Z"),
"grade" : "A",
"score" : 12
},
{
"date" : ISODate("2012-05-08T00:00:00Z"),
"grade" : "A",
"score" : 12
}
],
"name" : "Wendy'S",
"restaurant_id" : "30112340"
}
#Entity class
#Entity("restaurants")
public class Restaurant_M
{
#Id
public ObjectId _id;
#Property("borough")
public String town;
public String cuisine;
public String name;
#Property("restaurant_id")
public String r_id;
The Problem is that you don't give all information needed about the entity
You Can Just Use to map to entity :
dt.getCollection(Restaurant_M.class); then use DBObject
Or
dt.createQuery(Restaurant_M.class).field("").equal("to specify").get;
i made a DBO implementation as follows:
public Restaurant_M getByID (String id)
{
Query<Restaurant_M> query = createQuery().field("cuisine").equal(id);
return query.get();
}
and updated the main method as follows and it worked
public static void main(String[] args)
{
MongoClient client = new MongoClient("127.0.0.1:27017");
Morphia morphia = new Morphia();
Datastore ds = morphia.createDatastore(client, "test");
RestaurantDAO rdao = new RestaurantDAOImpl(Restaurant_M.class, ds);
Restaurant_M r = rdao.getByID("Hamburgers");
System.out.println(r);
r = ds.find(Restaurant_M.class).get();
System.out.println (r);
}

findBy to search inside an array in MongoRepository

I have a Mongo document which is like this :
db.user.find()
{
"_id" : ObjectId("560fa0c730a8e74bbd69c094"),
"name" : "abc",
"employee" : [{
"_id" : BinData(3,"v0m0V46pok94fVfwGkFVig=="),
"team" : "Dev Engineer",
}]
}
class User
{
String name;
String id;
}
class Employee
{
UUID id;
String team;
}
public interface EmployeeRepository extends MongoRepository<Employee, String>
{
#Query(value = "{ 'employee._id' : ?0 }")
Medication findByEmployeeId(UUID Id);
}
I want to find the employee by id and write a find method using the employee._id. Is there anyway to do this using MongoRepository, or should I return the entire array and loop through it? I tried the above method findByEmployeeId(UUID Id), but it does not work. I am not sure if the #Query annotation is necessary here. Please suggest!