How to use distinct with aggregate method for mongodb - mongodb

I have some conditions and a level to check while fetching records from collection using MongoDB.
For this I am using below
def cursorOutput = dataSetCollection.find(whereObject,criteriaObject)
Which is working fine. but I want to use distinct with combination to above query.
def distinctMIdList = dataSetCollection.distinct(hierarchyField,whereObject)
Above is the query for distinct. How to combine two query.
I tried below which is not working
def cursorOutput = dataSetCollection.find(whereObject,criteriaObject).distinct("manager id")
whereObject is a condition to fetch results and criteriaObject is fields to fetch.
Distinct query is giving me result with only Manager id field but I am looking for other field also(use of criteriaObject).
Finally how to combine above two query. I searched for pipeline where $distinct is not available.
Thank you.

Map function:
var mapFunction = function() {
if(/*your criteria*/) {
emit("manager_id", this.manager_id);
}
};
Reduce Function:
var reduceFunction = function(managerFiled,values){
return Array.unique(values);
}

Related

Update a collection in Mongo based on antothe collection with a "join"

I using Mongo version 4.2
I need to update a field in one collection as based on a field from another collection, according to a joining condiiton between the to collection.
In a regualr SQL, the update would be:
UPDATE col1, col2
SET col2.entityId = col1.Entity_ID
WHERE col1.id = col2.id
and col2.type='DEVICE';
I tried a method offered in one answer, but that does not seem to work, or I did not understand it correctly:
db.col1.find().forEach(function (doc1) {
var doc2 = db.col2.findOne({ id: doc1.id },{type:"DEVICE"});
if (doc2 != null) {
doc1.Entity_ID=doc2.entityId;
db.coll01.save(doc1);
}
});
Any ideas?
Thanks,
Tamar

Applying query filter like the one in codelab (Cloud Firestore) is not working

I'm using firestore for my project to store data , my issue is that i can not
filter data just the way codelab filter does .The result of that query gives me the whole collections docs which means the filter is not working.
I've tried many workarounds and find out that only when I cascade whereEqualto()
methods in one line I get what I want of specific docs , but this approach (cascading whereEqualTo inline) is not flexible when giving the user a way to filter searches.I just want to know why that code is not working for me.
// Does not work
Query query = mFirestore.collection("restaurants");
// Category (equality filter)
if (filters.hasCategory()) {
query = query.whereEqualTo("category", filters.getCategory());
}
// City (equality filter)
if (filters.hasCity()) {
query = query.whereEqualTo("city", filters.getCity());
}
This works:
query.whereEqualTo("realEstateType", realEstateType).whereEqualTo("propertyStatus", propertyStatus).whereEqualTo("propertyPhysicalStatus", propertyPhysicalConditionS).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
}
}
});
I figured it out ,It seems that I was not assigning to query object the filter as follows:
query = query.whereEqualTo("fieldPath" , ...);

Date comparison in MongoDB Filter

I am trying to create a Filter that will that will return the rows where at least one minute has passed from the stored transactionDate. I am not getting an error but it is not returning any rows. The transactionDate is a timestamp in MongoDB and is stored as "transactionDate" : ISODate("2016-09-30T20:29:19.448Z")
Thanks! \m/ \m/
var filter = Builders<MyDocument>.Filter.Eq("Genre", "Rock");
filter = filter & (Builders<MyDocument>.Filter.Lt(x => x.transactionDate, DateTime.Now.AddSeconds(Math.Abs(60) * (-1))));
using (var cursor = await MyCollection.Find(filter)
.Sort(Builders<MyDocument>.Sort.Ascending(x => x.artist).Ascending(x => x.rating)).ToCursorAsync())
{
// foreach...
}
The above code actually does work. I had an issue in the data causing no results to be returned. \m/ \m/

NumericRangeQuery in NHibernate.Search

I am creating a search, where the user can both choose an interval and search on a term in the same go.
This is however giving me trouble, since I have up until have only used the usual text query.
I am wondering how I am to go about using both a NumericRangeQuery and a regular term query. Usually I would use a query below:
var parser = new MultiFieldQueryParser(
new[] { "FromPrice", "ToPrice", "Description"}, new SimpleAnalyzer());
Query query = parser.Parse(searchQuery.ToString());
IFullTextSession session = Search.CreateFullTextSession(this.Session);
IQuery fullTextQuery = session.CreateFullTextQuery(query, new[] { typeof(MyObject) });
IList<MyObject> results = fullTextQuery.List<MyObject>();
But if I was to e.g. search the range FromPrice <-> ToPrice and also the description, how should I do this, since session.CreateFullTextQuery only takes one Query object?
you can create a single query that is a BooleanQuery combining all the conditions you want to be met.
For the ranges, heres a link to the synthax using the QueryParser:
http://lucene.apache.org/core/old_versioned_docs/versions/2_9_2/queryparsersyntax.html#Range Searches

Linq To NHibernate Plus sql user defined function

I have a rather large linq-to-nhibernate query. I now need to add a filter based on a user-defined function written in t-sql that i have to pass parameters into. In my case, I need to pass in a zipcode that the user types in and pass it to the t-sql function to filter by distance from this zip. Is this possible, or do i need to rewrite my query using the ICriteria api?
i did find a solution:
Note the NHibernate query (nquery) which has RegisterCustomAction:
private void CallZipSqlFunction(ListingQuerySpec spec, IQueryable<Listing> query)
{
var nQuery = query as NHibernate.Linq.Query<Listing>;
//todo: find some way to paramaterize this or use linq-to-nh and not criteria to call the function
// so i don thave to check for escape chars in zipcode
if (spec.ZipCode.Contains("'"))
throw new SecurityException("invalid character");
//yuck!
var functionString = "dbo.GetDistanceForListing('" + spec.ZipCode + "',{alias}.ID) as Distance";
//create a projection representing the function call
var distance = Projections.SqlProjection(functionString, new[] { "Distance" }, new IType[] { NHibernateUtil.String });
//create a filter based on the projection
var filter = Expression.Le(distance, spec.ZipCodeRadius.Value);
//add the distance projection as order by
nQuery.QueryOptions.RegisterCustomAction(x => x.AddOrder(Order.Asc(distance)));
//add teh distance filter
nQuery.QueryOptions.RegisterCustomAction(x => x.Add(filter));
}