Convert mongodb shell command to java code - spring

I'm new in mongodb and spring, i need to convert the following query to java code but i didn't find how to do it.
db.collection.aggregate([
{
$project: {
members: {
$concatArrays: [
[
{
"userID": "$userID",
"userType": "$userType"
}
],
{
$reduce: {
input: "$clients",
initialValue: [],
in: {
$concatArrays: [
"$$value",
[
{
userID: "$$this.userID",
userType: "$$this.userType"
}
],
"$$this.members"
]
}
}
}
]
}
}
},
{
$unwind: "$members"
},
{
$replaceRoot: {
newRoot: "$members"
}
}
])
I m stack in the $project part, i didn't find how to implement it in spring.
Can someone help me?

For use cases, where you find it hard to write a query in spring MongoDB java format, You can use the JSON/JavaScript code directly like this:
String jsonExpression = "{\"members\":{\"$concatArrays\":[[{\"userID\":\"$userID\",\"userType\":\"$userType\"}],{\"$reduce\":{\"input\":\"$clients\",\"initialValue\":[],\"in\":{\"$concatArrays\":[\"$$value\",[{\"userID\":\"$$this.userID\",\"userType\":\"$$this.userType\"}],\"$$this.members\"]}}}]}}";
AggregationOperation project = Aggregation.project().and(context -> context.getMappedObject(Document.parse(jsonExpression))).as("difference");
You can refer to my other answer here : Difference between "now" and a given date

Related

How to translate multi files by Google translation API?

I'd like to translate multi .pptx files. I'm trying to use Google translate API
My request json file is below.
{
"source_language_code": "ja",
"target_language_codes": ["en"],
"input_configs": {
"gcsSource": {
"inputUri": "gs://project_name/1.pptx"
},
"gcsSource": {
"inputUri": "gs://project_name/2.pptx"
}
},
"output_config": {
"gcsDestination": {
"outputUriPrefix": "gs://project_name/ja-en/"
}
}
}
I got this error, when I request translation API.
"description": "Invalid value at 'input_configs' (oneof), oneof field 'source' is already set. Cannot set 'gcsSource'"
Then I changed second gcsSource to gcsSource1
{
"source_language_code": "ja",
"target_language_codes": ["en"],
"input_configs": {
"gcsSource": {
"inputUri": "gs://project_name/1.pptx"
},
"gcsSource1": {
"inputUri": "gs://project_name/2.pptx"
}
},
"output_config": {
"gcsDestination": {
"outputUriPrefix": "gs://project_name/ja-en/"
}
}
}
The result was below.
"description": "Invalid JSON payload received. Unknown name \"gcsSource1\" at 'input_configs': Cannot find field."
gcsSource1 was used 2 times in the document
How should I chagne request json file, for translate multi files by translation API?
Endpoint is this. "https://translation.googleapis.com/v3/projects/project_name/locations/us-central1:batchTranslateDocument"
Note
Single file translation works fine.
{
"source_language_code": "ja",
"target_language_codes": ["en"],
"input_configs": {
"gcsSource": {
"inputUri": "gs://project_name/1.pptx"
},
},
"output_config": {
"gcsDestination": {
"outputUriPrefix": "gs://project_name/ja-en/"
}
}
}
The issue is with the curly braces used within input_configs. Since you want to use multiple elements, input_configs should be an array. So you should switch the curly braces with square braces as follows:
"input_configs": [
{
"gcsSource": {
"inputUri": "gs://bucket_name/1.pptx"
}
},
{
"gcsSource": {
"inputUri": "gs://bucket_name/2.pptx"
}
}
]
Also, you cannot change the names of json keys, as the structure of request.json which will be passed to the endpoint should be as mentioned in the documentation. This is the reason that when you change the key to “gcsSource1”, it gives you an error with “Cannot find field”.

GraphQL query to filter db document

I am writing an application using graphql, spring and mongodb. Here i want to perform some filter on db document using graphql.
Below is the representation of single document from mongo collection:
{
"data" : {
"attribute1" : [
{
"key":"val1"
"region":"US"
},{
"key":"val2"
"region":"UK"
}
]
"attribute2" : [
{
"nestedAttribute1": [
{
"key":"val3"
"region":"US"
},{
"key":"val4"
"region":"UK"
}
]
}
]
}
}
I want to filter the document, using GraphQL, with all the data where 'region' is 'US'.
Expected output:
{
"data" : {
"attribute1" : [
{
"key":"val1"
"region":"US"
}
],
"attribute2" : [
{
"nestedAttribute1": [
{
"key":"val3"
"region":"US"
}
]
}
]
}
}
Is it possible to write a generic query across all the attributes?
If not, are there any alternatives to GraphQL which support this filtering.
Here is the schema that is exact representation for mongo collection
https://pastebin.com/JxEPEGhp

Spring Data ElasticSearch Build In IN query returning partial match

I am new to elastic search spring data, Today I was trying to get In query working with Spring data ES repository.
I have to do a lookup for list of user names, and if its exactly match in the index, need to get those users back as result.
I tried to use the built in repository 'In' method to do so, but it returns partial matches, please help me to make this working like SQL IN query.
Here is my repository code:
public interface UserRepository extends ElasticsearchRepository<EsUser, String>
{
public List<EsUser> findByUserAccountUserNameIn(Collection<String> terms);
}
REQUEST:
{"terms":["vijay", "arun"], "type":"NAME"}
RESPONSE:
[
{
"userId": "236000",
"fbId": "",
"userAccount": {
"userName": "arun",
"urlFriendlyName": "arun",
},
"userProfile": {
},
"userStats": {
}
},
{
"userId": "6228",
"userAccount": {
"userName": "vijay",
"urlFriendlyName": "vijay",
},
"userProfile": {
},
"userStats": {
}
},
{
"userId": "236000",
"fbId": "",
"userAccount": {
"userName": "arun singh",
"urlFriendlyName": "arun-singh",
},
"userProfile": {
},
"userStats": {
}
}
{
"userId": "236000",
"fbId": "",
"userAccount": {
"userName": "vijay mohan",
"urlFriendlyName": "vijay-mohan",
},
"userProfile": {
},
"userStats": {
}
}
]
This is because your userAccount.userName field is an analyzed string, and thus, the two tokens arun and singh have been indexed. Your query then matches the first token, which is normal.
In order to prevent this and guarantee an exact match you need to declare your field as not_analyzed, like this:
#Field(index = FieldIndex.not_analyzed)
private String userName;
Then you'll need to delete your index and the associated template in /_template, restart your application so a new template and index are created with the proper field mapping.
Then your query will work.

How to select from array in Rethinkdb?

I have a field bidder with arrays and objects like this(it can be also empty):
[
[
{
"date":"08/17/1999"
},
{
"time":"07:15:23"
},
{
"increase":31.5
}
],
[
{
"date":"04/01/1998"
},
{
"time":"01:06:18"
},
{
"increase":10.5
}
]
]
How can I select first-array's increase value that means output should be 31.5.
In JavaScript
r.table('test')('bidder').nth(0)('increase').run(conn, callback)
In Python and Ruby
r.table('test')['bidder'][0]['increase'].run(conn)
Edit: Queries for all documents
If you need to do more complex things that just returning a value, you can use the general "form" with map
r.table('test').map(function(doc) {
return doc('bidder').nth(0)('increase')
}).run(conn, callback)

Validate a $Location in Firebase

I am trying to do some validation on incoming data into my firebase app. My structure is at the bottom. I have removed existing validation rules for clarity - however we can assume that reads and writes are allowed at the root rules level.
$categoryid will look something like this:
1234: {1:{...}, 2:{...}, 3:{...}}
I want to ensure that $categoryid (which is 1234 in the above example) is numerical - however the rule ".validate": "$categoryid.isNumeric()" results in an "no such method or property" error.
I could check for data.child($categoryid) in categories, however the variable doesn't exist at that level and results in an "unknown variable" error.
I'm sure I'm missing a trick here...
{
"rules": {
"categories": {
"$categoryid": {
"$itemid": {
"members": {
"$id": {
}
}
}
}
}
}
}
There is currently no good way to do this, but there is a hacky work around that involves storing the $categoryId in a field, then checking that that field is numeric.
Using these security rules:
{
"rules": {
"categories": {
"$categoryid": {
".validate": "'' + newData.child('meta/id') === $categoryId && newData.child('meta/id').isNumber()"
"meta": {},
"items": {
"$itemid": {
"members": {
"$id": {
}
}
}
}
}
}
}
}
We can then create a new category by running:
categoriesRef.child(1234).set({meta: {id: 1234}});
These rules will check that a) the $categoryId matches $categoryId/meta/id and that $categoryId/meta/id is a number.
To do this validation you can use RegEx /^[0-9]+$/
{
"rules": {
"categories": {
"$categoryid": {
.validate": "$categoryid.matches(/^[0-9]+$/)"
"$itemid": {
"members": {
"$id": {
}
}
}
}
}
}
}

Resources