MongoDB query two collections with sort orders - mongodb-query

Example: Let’s assume the following collections. ThrashMetalDocumentsCollection and SpeedMetalDocumentsCollection, both collections having the same HeavyMetalRecordDocument structure as shown below. How do I query and return ALL of the records in both collections and sort them by releaseDate (oldest first) and rating (high to low)? Thanks! \m/ \m/
static async Task getAllRecords()
{
var builder = Builders<HeavyMetalRecordDocument>.Filter;
//var filter;
using (var cursor = await ThrashMetalDocumentsCollection.Find()
.Sort(Builders<HeavyMetalRecordDocument>.Sort.Ascending(x => x.rating))
.ToCursorAsync())
{
while (await cursor.MoveNextAsync())
{
foreach (var doc in cursor.Current)
{
//Do Something…
}
}
}
}
public class HeavyMetalRecordDocument
{
public ObjectId Id { get; set; }
public String artist { get; set; }
public String title { get; set; }
public DateTime releaseDate { get; set; }
public int rating { get; set; } // 1-10
}

MongoDB is not a relational database, and as such, it cannot perform joins (which is what you are trying to accomplish). You probably want to think more about the structure of your database. Without knowing any more about what you are trying to do, I would suggest putting all types of albums into a single collection - putting in an additional field indicating the genre of the album.

Related

.net Core Many to Many relationship

I am trying to determine what would be the smartest way to accomplish this. I may be way way overthinking what I am trying to do, but here goes.
I have the following entities, simplified
public class Meet
{
public int Id { get; set; }
//various properties
public List<MeetComp> Competitors { get; set; }
}
public class Competitor
{
public int Id { get; set; }
// various properties
public List<MeetComp> Meets { get; set; }
[ForeignKey("GymManager")]
public int GymManagerId { get; set; }
public GymManager GymManager { get; set; }
}
public class GymManager
{
public int Id { get; set; }
//various properties
public List<Competitor> Competitors { get; set; }
}
public class MeetComp
{
public int Id { get; set; }
[ForeignKey("Competitor")]
public int CompetitorId { get; set; }
public Competitor Competitor { get; set; }
[ForeignKey("Meet")]
public int MeetId { get; set; }
public Meet Meet { get; set; }
}
So I am creating a razor page where I get a specific Gymmanager and load all the related competitors to display in a list, which I have working just fine.
However I need another list (on the same page) of the related competitors of the Gymmanager but also who have an entry in the "MeetComp" table by a specific meetid. So List #1 is all of my Competitors and List #2 is all of my Comptetitors that are registered for that Meet.
Would it be smarter to have EF pull the data I get the data the first time with a ThenInclude()? Then I write some logic to determine if they get added to list #2? or should I make another trip to the Database? Then if I do make another trip to the database is there an easy to way to query for the List of CompId's I already have?
So here's what I ended up doing is making another trip to the DB.
public async Task<IActionResult> GetRegisteredComps(List<int> Comps, int meetid)
{
if(Comps.Count == 0)
{
return Ok();
}
if(meetid == 0)
{
return BadRequest();
}
var query = _context.MeetsComps.Include(c => c.Competitor)
.AsQueryable();
query = query.Where(c => c.MeetId == meetid);
query = query.Where(c => Comps.Contains(c.CompetitorId));
var results = await query.ToListAsync();
return Ok(results);
}

One-to-Many relationship with ORMLite

The only examples I can find addressing this sort of scenario are pretty old, and I'm wondering what the best way is to do this with the latest version of ORMLite...
Say I have two tables (simplified):
public class Patient
{
[Alias("PatientId")]
[Autoincrement]
public int Id { get; set; }
public string Name { get; set; }
}
public class Insurance
{
[Alias("InsuranceId")]
[Autoincrement]
public int Id { get; set; }
[ForeignKey(typeof("Patient"))]
public int PatientId { get; set; }
public string Policy { get; set; }
public string Level { get; set; }
}
Patients can have multiple Insurance policies at different "levels" (primary, secondary, etc). I understand the concept of blobbing the insurance information as a Dictionary type object and adding it directly to the [Patient] POCO like this:
public class Patient
{
public Patient() {
this.Insurances = new Dictionary<string, Insurance>(); // "string" would be the Level, could be set as an Enum...
}
[Alias("PatientId")]
[Autoincrement]
public int Id { get; set; }
public string Name { get; set; }
public Dictionary<string, Insurance> Insurances { get; set; }
}
public class Insurance
{
public string Policy { get; set; }
}
...but I need the insurance information to exist in the database as a separate table for use in reporting later.
I know I can join those tables in ORMLite, or create a joined View/Stored Proc in SQL to return the data, but it will obviously return multiple rows for the same Patient.
SELECT Pat.Name, Ins.Policy, Ins.Level
FROM Patient AS Pat JOIN
Insurance AS Ins ON Pat.PatientId = Ins.PatientId
(Result)
"Johnny","ABC123","Primary"
"Johnny","987CBA","Secondary"
How can I map that into a single JSON response object?
I'd like to be able to map a GET request to "/patients/1234" to return a JSON object like:
[{
"PatientId":"1234",
"Name":"Johnny",
"Insurances":[
{"Policy":"ABC123","Level":"Primary"},
{"Policy":"987CBA","Level":"Secondary"}
]
}]
I don't have a lot of hope in this being do-able in a single query. Can it be done in two (one on the Patient table, and a second on the Insurance table)? How would the results of each query be added to the same response object in this nested fashion?
Thanks a ton for any help on this!
Update - 4/29/14
Here's where I'm at...In the "Patient" POCO, I have added the following:
public class Patient
{
[Alias("PatientId")]
[Autoincrement]
public int Id { get; set; }
public string Name { get; set; }
[Ignore]
public List<Insurance> Insurances { get; set; } // ADDED
}
Then, when I want to return a patient with multiple Insurances, I do two queries:
var patientResult = dbConn.Select<Patient>("PatientId = " + request.PatientId);
List<Insurance> insurances = new List<Insurance>();
var insuranceResults = dbConn.Select<Insurance>("PatientId = " + patientResult[0].PatientId);
foreach (patientInsurance pi in insuranceResults)
{
insurances.Add(pi);
}
patientResult[0].Insurances = insurances;
patientResult[0].Message = "Success";
return patientResult;
This works! I get nice JSON with nested items for Insurances while maintaining separate related tables in the db.
What I don't like is that this object cannot be passed back and forth to the database. That is, I can't use the same nested object to automatically insert/update both the Patient and InsurancePolicy tables at the same time. If I remove the "[Ignore]" decorator, I get a field in the Patient table called "Insurances" of type varchar(max). No good, right?
I guess I'm going to need to write some additional code for my PUT/POST methods to extract the "Insurances" node from the JSON, iterate over it, and use each Insurance object to update the database? I'm just hoping I'm not re-inventing the wheel here or doing a ton more work than is necessary.
Comments would still be appreciated! Is Mythz on? :-) Thanks...
An alternate more succinct example:
public void Put(CreatePatient request)
{
var patient = new Patient
{
Name = request.Name,
Insurances = request.Insurances.Map(x =>
new Insurance { Policy = i.Policy, Level = i.Level })
};
db.Save<Patient>(patient, references:true);
}
References are here to save the day!
public class Patient
{
[Alias("PatientId")]
[Autoincrement]
public int Id { get; set; }
public string Name { get; set; }
[Reference]
public List<Insurance> Insurances { get; set; }
}
public class Insurance
{
[Alias("InsuranceId")]
[Autoincrement]
public int Id { get; set; }
[ForeignKey(typeof("Patient"))]
public int PatientId { get; set; }
public string Policy { get; set; }
public string Level { get; set; }
}
I can then take a JSON request with a nested "Insurance" array like this:
{
"Name":"Johnny",
"Insurances":[
{"Policy":"ABC123","Level":"Primary"},
{"Policy":"987CBA","Level":"Secondary"}
]
}
...to create a new record and save it like this:
public bool Put(CreatePatient request)
{
List<Insurance> insurances = new List<Insurance>();
foreach (Insurance i in request.Insurances)
{
insurances.Add(new Insurance
{
Policy = i.Policy,
Level = i.Level
});
}
var patient = new Patient
{
Name = request.Name,
Insurances = insurances
};
db.Save<Patient>(patient, references:true);
return true;
}
Bingo! I get the new Patient record, plus 2 new records in the Insurance table with correct foreign key references back to the PatientId that was just created. This is amazing!
First you should define a foreign collection in Patient class. (with get and set methods)
#ForeignCollectionField
private Collection<Insurance> insurances;
When you query for a patient, you can get its insurances by calling getInsurances method.
To convert all into a single json object with arrays inside you can use a json processor. I use Jackson (https://github.com/FasterXML/jackson) and it works very well. Below will give you json object as a string.
new ObjectMapper().writeValueAsString(patientObject);
To correctly map foreign fields you should define jackson references. In your patient class add a managed reference.
#ForeignCollectionField
#JsonManagedReference("InsurancePatient")
private Collection<Insurance> insurances;
In your insurance class add a back reference.
#JsonBackReference("InsurancePatient")
private Patient patient;
Update:
You can use Jackson to generate objects from json string then iterate and update/create database rows.
objectMapper.readValue(jsonString, Patient.class);

RavenDB Include though collection

I'm struggling with the include function in RavenDB. In my model I have a blog post that holds a list of comments. The comment class that's used in this list holds a reference to a user.
public class BlogPost
{
public string Id { get; set; }
public List<Comment> Comments { get; set; }
public BlogPost()
{
Comments = new List<Comment>();
}
}
public class Comment
{
public string Id { get; set; }
public string Text { get; set; }
public string UserId { get; set; }
}
What I want to do is to get the blogpost and get a list of comments with the details of the user that wrote the comment to display in the UI, without querying the server for every single user (N+1).
I would be happy with some pointers on how to solve this. Thanks!
You can do that using something like:
session.Include<BlogPost>(b=>b.Comments.Select(x=>x.UserId)).Load(1);
I think this page would answer your question.
You can load multiple documents at once:
var blogSpots = session.Include<BlogPost>(x => x.Comments.Select(x=>x.UserId))
.Load("blogspot/1234", "blogspot/4321");
foreach (var blogSpot in blogSpots)
{
foreach (var userId in blogSpot)
// this will not require querying the server!!!
var cust = session.Load<User>(userId);
}

RavenDb Select() downcasts instead of selecting the neccessary fields

public class PersonBrief
{
public int Id { get; set; }
public string Picture { get; set; }
public PersonBrief(Person person)
{
Id = person.Id;
Picture = person.Picture;
}
}
public class Person : PersonBrief
{
public string FullName { get; set; }
}
var results = session.Query<Person>()
.Select(x => new PersonBrief(x))
.ToList();
Assert.IsNull(results[0] as Person); // Fails
Is this a bug? If not, what would be the correct way to select only the fields i'm interested in?
It would work if you move the .ToList before the .Select, but that would be doing the work on the client.
If you want to do it on the server, you need to use As in your query, and you need a static index that does a TransformResults. See these docs.

RavenDb: Find movies that Actor X is NOT acting in

I'm new to RavenDb and I've encountered the following problem, which is pretty easy to solve in SQL databases, but not so easy in RavenDb (it seems).
Given my classes:
//document collection
public class Movie
{
public string Id { get; set; }
public string Title { get; set; }
public List<MovieActor> Actors { get; set; }
}
public class MovieActor
{
public string ActorId { get; set; }
public string CharacterName { get; set; }
public DateTime FirstAppearance { get; set; }
}
//document collection
public class Actor
{
public string Id { get; set; }
public string Name { get; set; }
}
Finding every movie that Leonardo DiCaprio is acting in is very easy and efficient with the following Map index:
public class Movies_ByActor : AbstractIndexCreationTask<Movie>
{
public Movies_ByActor()
{
Map = movies => from movie in movies
from actor in movie.Actors
select new
{
MovieId = movie.Id,
ActorId = actor.ActorId
};
}
}
But this is not what I want to achieve, I want the opposite... to find all the movies where Leonardo DiCaprio is not acting.
I have also tried the following query:
var leonardoActorId = "actor/1";
var movies = from movie in RavenSession.Query<Movie>()
where !movie.Actors.Any(a => a.ActorId.Equals(leonardoActorId))
select movie;
But this will only give me an exception:
System.InvalidOperationException: Cannot process negated Any(), see RavenDB-732 http://issues.hibernatingrhinos.com/issue/RavenDB-732
Anyone know how to achieve this the proper way in RavenDb ?
Using the method described in my blog post here:
http://www.philliphaydon.com/2012/01/18/ravendb-searching-across-multiple-properties/
You can create an index with an array of ActorIds:
public class Movies_ByActor : AbstractIndexCreationTask<Movie>
{
public Movies_ByActor()
{
Map = movies => from s in movies
select new
{
Actors = s.Actors.Select(x => x.ActorId)
};
}
public class ActorsInMovie
{
public object[] Actors { get; set; }
}
}
Then you can search where the movie doesn't contain the actor you want:
var result = session.Query<Movies_ByActor.ActorsInMovie, Movies_ByActor>()
.Where(x => x.Actors != (object)"actors/1")
.As<Movie>();
Since the object we're querying against is different to the result, we need to specify As<T> to tell RavenDB what the type of the object actually returned is.
Working sample: http://pastie.org/7092908