Spring Mongo Aggregation that doesn't return duplicates values - spring

I'm working on Spring while using Mongo as database. I have some collections and elements inside it. I'm trying to create a function that will return a random element from collection on every call but not return same element twice.
I have this in my repository class:
#Aggregation(pipeline = {"{'$match':{'typeOfAdventureHolidays':'summerCamps'}}", "
{$sample:{size:1}}"})
AggregationResults<AdventureHolidays> randomSummerCamps();
This return me a random value but also show me same value twice, while I want to avoid that.
I tried to search for some answers but I just founded a couple of ways to prevent it but to not show duplicate elements, no to not return same element twice.
So my code is like this.
Repository
#Aggregation(pipeline = {"{'$match':{'typeOfAdventureHolidays':'summerCamps'}}", "
{$sample:{size:1}}"})
AggregationResults<AdventureHolidays> randomSummerCamps();
ServiceImpl
#Override
public List<AdventureHolidays> getRandomSummerCamps() {
return Collections.singletonList(adventureHolidaysRepository.randomSummerCamps().
getMappedResults().stream().findFirst().orElse(null));
}
Controller
#GetMapping("/getRandomSummerCamps")
public String getRandomSummerCamps(Model model) {
model.addAttribute("randomSummerCamps",
adventureHolidaysService.getRandomSummerCamps());
return "randomSummerCamps";
}
If I need to provide something else I'm here, I tried to find something that will be useful but no success

Related

Neo4j 6 Spring boot 2.4 migrate driver session query

I am trying to migrate to neo4j 6. Whats the equivalent of this method in neo4j6?
The Result here contains: {ref=Employee.... etc, so the actual Java objects.
//org.neo4j.ogm.session.Session is autowired
#GetMapping("/companies/{companyId}/refs")
public Result getCompanyRefs(#PathVariable final String companyId)
{
String query = "MATCH (company:Company)-[ref]-(refObj) where company.id=\"" + companyId + "\" RETURN company,ref,refObj";
return this.session.query(query, Collections.emptyMap());
}
I tried with the new neo4j driver like so:
//org.neo4j.driver.Driver is autowired
#GetMapping("/persons/{personId}/refs")
public Result getPersonRefs(#PathVariable final String personId)
{
String query = "MATCH (person:Person)-[ref]-(refObj) where person.id=\"" + personId + "\" RETURN person,ref,refObj";
return this.driver.session().run(query, Collections.emptyMap());
}
but this gives a Result which is not convertable to my #Node (entity) classes. The previous version gave a Result which contained the actual java objects(mapped to classes).
the result here is:Record<{person: node<7>, ref: relationship<8>, refObj: node<0>}>
Basically the main thing is: i need the nodes mapped to java objects. But i need them via a cypher query, because i need to do some things on the (Result) Nodes before deleting the relationships between them.
so it turns out it does give back the things i need.
Result result = this.getPersonRefs(id);
result.list().forEach((entry) -> {
The problem was that for example neither entry.get("refObj").asObject(), nor asNode() actually gave back what i thought it was supposed to give back.
The Solution:
entry.get("refObj").asMap()
this gives back the actual properties of the object. Then you just need to convert it to MyClass.class with an ObjectMapper.

How to retrieve data by property in Couchbase Lite?

My documents have the property docType that separated them based on the purpose of each type, in the specific case template or audit. However, when I do the following:
document.getProperty("docType").equals("template");
document.getProperty("docType").equals("audit");
The results of them are always the same, it returns every time all documents stored without filtering them by the docType.
Below, you can check the query function.
public static Query getData(Database database, final String type) {
View view = database.getView("data");
if (view.getMap() == null) {
view.setMap(new Mapper() {
#Override
public void map(Map<String, Object> document, Emitter emitter) {
if(String.valueOf(document.get("docType")).equals(type)){
emitter.emit(document.get("_id"), null);
}
}
}, "4");
}
return view.createQuery();
}
Any hint?
This is not a valid way to do it. Your view function must be pure (it cannot reference external state such as "type"). Once that is created you can then query it for what you want by setting start and end keys, or just a set of keys in general to filter on.

Fetch history of records using LINQ

I am using entity framework with repository pattern and unit of work objects..
I have an entity Request with properties "RequestId", "OldRequestId", which can be accessed using requestRepository object.
eg: requestRepostiory.GetAll(), requestRepository.GetFiltered(r=> r.Requestid =10)
If I pass a RequestId, it should retrieve me the specific record.
If the OldRequestId is not null in the retrieved record, it should bring the old request data as well.
It should go on until the OldRequestId is null.
Simple way would be something like this:
public static IEnumerable<Data> GetRecursive(int id)
{
while (true)
{
var tmp = GetFiltered(x => x.Requestid == id);
yield return tmp;
if (tmp.OldRequestId.HasValue)
id = tmp.OldRequestId.Value;
else
yield break;
}
}
Please note, that this code would run make multiple queries towards the database. Performance won't be the best, but it might work for your scenario.

Cannot figure where clause in Linq that excludes values.

I am creating a repository that using entity framework (also domain objects) and I need to query all records that does not contain value "BADGE/" (undesired value). I found a method that is ".Contains", but cannot find something equivalent to "notContains" or way to exclude records that have the undesired value. I would like the replace "p.Lname.Contains("BADGE/") with something like "p.Lname.NotContains("BADGE/") or something like that where it excludes the values during the return. Here is what I have so far:
public IQueryable<Personnel> NoBadgePersonnels
{
get {
return Context.Personnels.Where(p => p.Lname.Contains("BADGE/"));
}
}
additionally, this what my context looks like:
public class EmployeeRepository
{
private readonly EFContextProvider<EmployeeDbContext>
_contextProvider = new EFContextProvider<EmployeeDbContext>();
private EmployeeDbContext Context
{
get { return _contextProvider.Context; }
}
thanks community
Nick
Try:
return Context.Personnels.Where(p => p.Lname.IndexOf("BADGE/") == -1);
This excludes any strings which contain your target string.

How do I store a comma-separated list in Orchard CMS?

Using Orchard CMS, I am dealing with a record and a part proxy, but cannot figure out how to save it into the DB. In fact, I confess I don't even know how to get the items I'm trying to save into this paradigm. I was originally using enum's for choices:
MyEmum.cs:
public enum Choices { Choice1, Choice2, Choice3, Choice4 }
MyRecord.cs:
public virtual string MyProperty { get; set; }
MyPart.cs:
public IEnumerable<string> MyProperty
{
get
{
if (String.IsNullOrWhiteSpace(Record.MyProperty)) return new string[] { };
return Record
.MyProperty
.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries)
.Select(r => r.Trim())
.Where(r => !String.IsNullOrEmpty(r));
}
set { Record.MyProperty = value == null ? null : String.Join(",", value); }
}
Now, in my service class, I tried something like:
public MyPart Create(MyPartRecord record)
{
MyPart part = Services.ContentManager.Create<MyPart>("My");
...
part.MyProperty = record.MyProperty; //getting error here
...
return part;
}
However, I am getting the following error: Cannot implicitly convert 'string' to System.Collections.Generic.IEnumerable<string>'
Essentially, I am trying to save choices from a checkboxlist (one or more selections) as a comma-separated list in the DB.
And this doesn't even get me over the problem of how do I use the enum. Any thoughts?
For some background:
I understand that the appropriate way to handle this relationship would be to create a separate table and use IList<MyEnum>. However, this is a simple list that I do not intend to manipulate with edits (in fact, no driver is used in this scenario as I handle this on the front-end with a controller and routes). I am just capturing data and redisplaying it in the Admin view for statistical/historical purposes. I may even consider getting rid of the Part (considering the following post: Bertrand's Blog Post.
It should be:
part.MyProperty = new[] {"foo", "bar"};
for example. The part's setter will store the value on the record's property as a comma-separated string, which will get persisted into the DB.
If you want to use enum values, you should use the Parse and ToString APIs that .NET provide on Enum.

Resources