is there a way to change the CAS APEREO collection structure? - java

I am planning to implement CAS with MongoDB authentication and also planning to use existing MongoDB collection which is not following the expected Document scheme as mentioned in apreo documentation.
As per documents,
Accounts are expected to be found as such in collections:
{
"username": "casuser",
"password": "34598dfkjdjk3487jfdkh874395",
"first_name": "john",
"last_name": "smith"
}
is there way to customize the username and password attributes something like below
{
"_id" : "000debf7-ee17-42ec-b267-9028b721cd57",
"firstName" : "Steve Ward",
"lastName" : "Steve Ward",
"emailAddress1" : "test#inter.com",
"status" : "active",
"users" : [
{
"userName" : "weldoneinc",
"password" : "KJH8u3lRYvm82EbiGjKZs7exPbY=",
"createUser" : "TEST",
"createDate" : ISODate("2020-05-22T15:28:54.439+0000"),
"updateUser" : "TEST",
"updateDate" : ISODate("2020-05-22T15:28:54.439+0000")
}
]
}

Related

I am working with Java and Springboot. Is it possible to retrieve only nested json field from a Json document in mongo

{
"_id" : ObjectId("dde3431134247d401b1cef"),
"_resourceId" : "fwf4-fefre4-ffdfwsc",
"organizationId" : 343203,
"domains" : [
{
"_resourceId" : "da7-cwcwe-2432d",
"name" : "d12.net",
"tenantId" : "A1650",
"application" : "TEST",
"activeInd" : true,
"subdomains" : [
{
"_resourceId" : "fw243-weded3-2eddas",
"name" : "name1",
"clientName" : "Andrew",
"phoneNumber" : "8573458456",
"email" : "modalwindow#gmail.com",
},
{
"_resourceId" : "bce3-cwdd32ede-23ede",
"name" : "name2",
"clientName" : "client2",
"phoneNumber" : "9999999999",
"email" : "test#gmail.com",
}
]
}
]
}
I am using Springboot and MongoTemplate for the find Query. If I want to retrieve a subdomain based on "domains.subdomain.name" field, can I get only the subdomain json from a mongo query, or do I get the entire document and then iterate and filter the subdomain in my java code.
Use $unwind and then $replaceWith
db.collection.aggregate([
{
$match: {
"domains.subdomains.name": "name1"
}
},
{
$unwind: "$domains"
},
{
$unwind: "$domains.subdomains"
},
{
$match: {
"domains.subdomains.name": "name1"
}
},
{
$replaceWith: "$domains.subdomains"
}
])
mongoplayground

How to query an array in array of dictionaries in MongoDB?

I have a following mongoDB document structure -
db.menus.findOne()
{
"_id" : ObjectId("5cf25412326c3f4f26df039b"),
"restaurantId" : "301728",
"items" : [
{
"itemId" : "CEBM4H41JR",
"name" : "Crun Chicken",
"imageUrl" : "",
"price" : 572,
"attributes" : [
"Tasty",
"Spicy"
]
},
{
"itemId" : "53Q0XS3HPR",
"name" : "Devils Chicken",
"imageUrl" : "",
"price" : 595,
"attributes" : [
"Gravy",
"Salty"
]
}
]
}
I am trying to write a query to get all the menus based on the "attributes" field under "items" in the document.
I have done the following to get the menus if "name" of "items" is given and I am getting a result -
db.menus.find({ 'items' : {$elemMatch : {'name' : {$regex : "Chicken Thali", $options: 'i' }}}}).pretty()
I have tried this for getting the result for attributes but this is not working -
db.menus.find({'items' : {$elemMatch : {'attributes' : {$all : [{$regex : "Tasty", $options: 'i' }]}}}})
How do I get the list and I also want to write this query for mongoRepository in a spring boot application?
Further, based on the restaurantId's obtained, I have to query restaurant collection in order to find all the restaurants in restaurants collection having the following structure -
{
"_id" : ObjectId("5cf2540e326c3f4f26de93dd"),
"restaurantId" : "301728",
"name" : "Desire Foods",
"imageUrl" : "https://b.zmtcdn.com/data/pictures/8/301728/d690ccb500d746530f56e1d637949da2_featured_v2.jpg",
"latitude" : 28.4900591,
"longitude" : 77.3066401,
"attributes" : [
"Chinese",
" Fast Food",
" Bakery"
],
"opensAt" : "09:30",
"closesAt" : "22:30"
}
Is the whole operation possible in a single query?
I think you can modify your query to use $in instead of $all.
To achieve your intended result, you can try:
db.collection.aggregate([
{
"$match": {
"items": {
"$elemMatch": {
"attributes": {
"$in": [
"Tasty"
]
}
}
}
}
},
{
"$lookup": {
"from": "restaurant",
"localField": "restaurantId",
"foreignField": "restaurantId",
"as": "restaurants"
}
},
{
"$unwind": "restaurants"
},
{
"$replaceRoot": { "newRoot": "$restaurants" }
}
])
Use $match at appropriate stages as needed to limit the documents pulled in memory

Spring Java Mongodb Aggregation check userId in array

I have a MongoDB database with users and questions.
My Question document:
{
"_id" : "b943d57a-f4c3-4394-86f7-dd1d1b5e2563",
"_class" : "org.company.app.model.Question",
"statement" : "First question for testing purposes",
"userMail" : "themail#mail.com",
"responses" : [
{
"responseId" : "6b60e900-0fec-47d2-8853-e1ea3508abe6",
"responseType" : "TEXT",
"mail" : "themail2#mail.com",
"responseTime" : ISODate("2017-11-22T11:23:10.848Z"),
"data" : "New Response 1",
"likes" : [
"themail3#mail.com",
"themail5#mail.com"
],
"dislikes" : [],
"state" : "PUBLISHED",
"stateTime" : ISODate("2017-11-22T11:23:10.848Z")
}
],
"categories" : [
"Category1",
"Category2",
"Category3"
],
"creationTimestamp" : ISODate("2017-10-26T14:50:12.717Z"),
"lastUpdateTimestamp" : ISODate("2017-11-02T15:35:20.818Z"),
"deleted" : false,
"active" : true,
"state" : "PUBLISHED"
}
and the user document:
{
"_id" : "1f4b5091-c755-4083-880e-e1c4696f7236",
"_class" : "org.company.app.model.User",
"allowsComms" : true,
"registrationConfirmed" : false,
"placeOfWork" : "Urban records",
"name" : "John",
"surname" : "Doe",
"mail" : "themail3#mail.com",
"phone" : "[ \"1111111111\" , \"2222222222222\"]",
"birthDate" : ISODate("1971-12-10T23:00:00.000Z"),
"gender" : "MALE",
"nationality" : "US",
"language" : "en",
"socialNetworks" : {
"INSTAGRAM" : "#instagram",
"TWITTER" : "#twitter"
},
"specialty" : "alternative rock",
"subspecialty" : "sub_3",
"creationTimestamp" : ISODate("2017-10-31T10:13:12.131Z"),
"lastUpdateTimestamp" : ISODate("2017-11-13T10:23:37.637Z"),
"deleted" : false,
"active" : true,
"profileImage" : "image"
}
From that point, I'm creating a new aggregation to join both collections, get user information and count likes and dislikes instead of return all the user ids at that array.
public List<JoinedResponse> getResponses(String userId, String questionId, long itemsPerPage, long requestedPage) {
Assert.hasLength(questionId, "questionId cannot be null or empty");
MatchOperation questionIdMatch = Aggregation.match(new Criteria("_id").is(questionId));
MatchOperation responsesStateMatch = Aggregation.match(Criteria.where("responses.state")
.in(QuestionState.PUBLISHED.toString(), QuestionState.APPROVED.toString()));
LookupOperation userInfoLookUpOperation = LookupOperation.newLookup().from("User").localField("$responses.mail").foreignField("mail")
.as("userInfo");
ProjectionOperation fieldsProjectionOperation = Aggregation.project(Fields.from(
Fields.field("responseId", "$responses.responseId"),
Fields.field("responseType", "$responses.responseType"),
Fields.field("mail", "$responses.mail"),
Fields.field("responseTime", "$responses.responseTime"),
Fields.field("data", "$responses.data"),
Fields.field("state", "$responses.state"),
Fields.field("userName", "$userInfo.name"),
Fields.field("userSurname", "$userInfo.surname"),
Fields.field("profileImage", "$userInfo.profileImage")))
.and("$responses.likes").size().as("likes")
.and("$responses.dislikes").size().as("dislikes");
// Creates the Aggregation: THE ORDER IS IMPORTANT!!!
Aggregation ag = Aggregation.newAggregation(
questionIdMatch,
Aggregation.unwind("responses"),
responsesStateMatch,
userInfoLookUpOperation,
Aggregation.unwind("userInfo"),
fieldsProjectionOperation,
Aggregation.project("responseId", "userName", "userSurname", "mail", "responseType", "responseTime",
"data", "likes", "dislikes", "profileImage", "state"/*, "isLiked"*/),
Aggregation.skip((long) ((requestedPage - 1) * itemsPerPage)),
Aggregation.limit(itemsPerPage));
logger.debug(ag.toString());
AggregationResults< JoinedResponse > output = mongoTemplate.aggregate(ag, "Question",
JoinedResponse);
Well, at this point, I need to know if the userId is in the liked or disliked list and I have spend a lot of hours investigating with no result. Of course, I would like to do it with aggregation.
Any help will be appreciated.
Thank you!

Spring Data Tool Suite - Bulk Insert of objects

I am developing an API that create a list of Questions , and would like to know check if STS have any native capability that can support bulk insert , or if i have to create a custom query using #Query annotation?
I have refer to this Spring Data MongoDB support bulk insert/save , i would like to check if an unique ObjectId still be generated through bulk insert/save?
Sample definition i am expecting , where each question is differentiated with an unique Id.
questions": [
{
"id" : "01-QuestionId",
"type" : "multiple",
"question" : "What is your Gender?",
"options" : [
{
"key" : "a",
"value" : "Male"
},
{
"key" : "b",
"value" : "Female"
}
],
"survey":{
"id": "123",
"name": "Test1",
"description": "First Survey"
}
},
{
"id" : "02-QuestionId",
"type" : "multiple",
"question" : "What is your income?",
"options" : [
{
"key" : "a",
"value" : "1000"
},
{
"key" : "b",
"value" : "2000"
}
],
"survey":{
"id": "123",
"name": "Test1",
"description": "First Survey"
}
}
]
Thanks all!
Robin
Found out after deeper research in Spring Data.
We can just use save() or insert() interface from MongoRepository class.
For example
final List savedQuestions = questionRepository.save(questions);

Morphia: Filter element in ArrayList using Morphia

I have a Java class called Project with a users ArrayList<User> property that contains User objects.
My projects collection looks like
[
{
"_id" : ObjectId("56410150d277de02f3b67495"),
"name" : "my-project",
"users" : [
{
"id" : "58b5eb81-35b2-4719-87ad-e5eea76a478f",
"name" : "john",
"lastName" : "Doe"
}
]
}
]
I want to find a user with a specific UUID inside this property. I can find it in MongoDB with the following query:
db.getCollection('projects').find({"users.id": "58b5eb81-35b2-4719-87ad-e5eea76a478f"})
How do I get the same results using Morphia?
I've tried this:
Project project = datastore.createQuery(Project.class).filter("users.id", user_id).get();
And this:
Project project = datastore.find(Project.class, "users.id", user_id).get();
But with no luck :(
Any help?
I expect getting:
{
"id" : "58b5eb81-35b2-4719-87ad-e5eea76a478f",
"name" : "john",
"lastName" : "Doe"
}

Categories

Resources