Mongo DB $near query in c#? - c#

var query ="{'Geo':{'$near': {'$geometry': {'type': 'Point' ,'coordinates':[]} }}}";
var parsing = BsonDocument.Parse(query);
var qwithcoor = parsing["Geo"]["$near"]["$geometry"]["coordinates"].AsBsonArray;
qwithcoor.AddRange(coordinates);
parsing["Geo"]["$near"].AsBsonDocument.Add("$maxDistance", radius);
var collection = database.GetCollection<BsonDocument>("mycollection");
var documents = await collection.Find(parsing).ToListAsync();
I want to do this with Builders<BsonDocument>.Filter. Like this:
var query=Builders<BsonDocument>.Filter.Near();
var documents=await collection.Find(query).ToListAsync();
do I use Near after the Filter? What are the Near parameters?

I solve this with
var gp =new GeoJsonPoint<GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(coordinates[0], coordinates[1]));
var query=Builders<BsonDocument>.Filter.Near("Geo",gp,radius);
var result = await col.Find(query).ToListAsync();

Related

How do I find all collections with a certain string in the name in my MongoDB database?

I've got a database containing several collections. Some has got a name like "carpenter_title_year_version". Others has got a name like "plumber_title_year_version". How do I set up a filter to retrieve all collections where the string "carpenter" is in the collectionname?
I'm thinking something like:
var filterBuilder = Builders<GroupEntity>.Filter;
var projectionBuilder = Builders<GroupEntity>.Projection;
var collection = Database.GetCollection<GroupEntity>("dbname");
var filter = filterBuilder.ElemMatch("carpenter..., ?"); //<--- ???
var projection = projectionBuilder.Exclude("_id");
var list = await collection.Find(filter).Project(projection).ToListAsync();
There's (and an async version of it)
IAsyncCursor<MongoDB.Bson.BsonDocument> IMongoDatabase.ListCollections(ListCollectionsOptions options = null, CancellationToken cancellationToken = null);
You can use the filter from the collection options to match the collection name.
// <CAPS INSIDE> are wildcards
var _client = new MongoClient(#"connection string");
var _database = _client.GetDatabase("<DATABASE NAME>");
var bre = new BsonRegularExpression("<YOUR REGEX PATTERN>");
var copt = new ListCollectionsOptions{ Filter =
Builders<BsonDocument>.Filter.Regex ("name", bre )
};
var collectionsWithMatchingNames = _database.ListCollections(copt).ToList().Select (col => col["name"]);
Only then you get your particular collection, like:
foreach (var x in collectionsWithMatchingNames)
var collection = _database.GetCollection<BsonDocument>(x);

Find in subdocument MongoDb

I need to first find the document by _id.
Then in the document to find subdocument which have a Time field is greater than the parameter lastTime
var filter = builder.Eq("_id", symbol) & builder.Gt("Update.Time", lastTime);
var result = await MongoDb.CollectionName.Find(filter).ToListAsync();
This example has a result of 0.
How to write this query? I need get this subdocument "Update" or last 3 sub-subdocument
The document has the following structure
{
{"_id", symbol},
{"Update", [
{"_id", number}, {"Time", sometime}, {"Version", versionNumber},
{"_id", number}, {"Time", sometime}, {"Version", versionNumber},
{"_id", number}, {"Time", sometime}, {"Version", versionNumber},
{"_id", number}, {"Time", sometime}, {"Version", versionNumber},}
]
}
If mongodb console will work an example:
> db.doc.save({
"_id":"123",
"update":[
{"_id":'1', "time":'345', "Version":'3'},
{"_id":'2', "time":'234', "Version":'4'}
]
})
> db.doc.findOne( { _id:"123", "update.time":{ $gt: 344 } } )
Then for C# Will can you to try ?
var collection = _database.GetCollection<BsonDocument>("name");
var filter = Builders<BsonDocument>.Filter.Gt("update.time", 344);
var result = await collection.Find(filter).ToListAsync();
This example
UPD This can be:
var collection = _database.GetCollection<BsonDocument>("name");
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Eq("_id", id) & builder.Gt("update.time", 344);
var result = await collection.Find(filter).ToListAsync();
Try using lambda expressions:
var lastTime = 1;
var result = collection.Find(x => x.Update.Contains(lastTime));

How to get result of rollup query for a custom entity

When trying to get the records I get this error
The 'Rollup' method does not support entities of type 'new_X'.
This is my code
RollupRequest req = new RollupRequest();
QueryExpression qe = new QueryExpression();
qe.EntityName = "new_x";
qe.ColumnSet = new ColumnSet(true);
req.Query = qe;
req.Target = new EntityReference("new_newpost", new Guid("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));
req.RollupType = RollupType.Related;
RollupResponse resp = (RollupResponse)xrm.Execute(req);
How can I get the results of rollup query
Thanks in advance
For custom entities you can do the fallowing
var rollupQuery = xrm.GoalRollupQuerySet.Where(c => c.Id == x.new_RecordstoRun.Id).First();
var result = xrm.RetrieveMultiple(new FetchExpression(rollupQuery.FetchXml));
But - How can I add a 'Skip' or 'Take' Linq to this?
You can only use the RollupRequest on a certain set of entities described on the MSDN.
So this will never work for "new_x" or "new_newpost".
This article has a correct demonstration of the RollupRequest using opportunity and account.
I would suggest just creating your own custom QueryExpression to retrieve all "new_x" and then link to "new_newpost" with LinkEntities.
Here is my code so get the results of RollupQuery
List<Guid> GetAllResultsFromRollupQuery(XrmServiceContext xrm, Guid rollupQueryId)
{
var rollupQuery = xrm.GoalRollupQuerySet.Where(v => v.Id == rollupQueryId).First();
var qa = GetQueryExpression(xrm, rollupQuery.FetchXml);
qa.PageInfo.Count = 1000;
qa.ColumnSet.AddColumn(rollupQuery.QueryEntityType + "id");
var result = new List<Guid>();
EntityCollection ec = null;
do
{
ec = xrm.RetrieveMultiple(qa);
ec.Entities.ToList().ForEach(v => result.Add((Guid)v.Attributes[rollupQuery.QueryEntityType + "id"]));
qa.PageInfo.PageNumber += 1;
} while (ec.MoreRecords == true);
return result;
}
QueryExpression GetQueryExpression(XrmServiceContext xrm, string fetchXml)
{
var req = new FetchXmlToQueryExpressionRequest { FetchXml = fetchXml };
var result = (FetchXmlToQueryExpressionResponse)xrm.Execute(req);
return result.Query;
}

Select all rows but only specific columns

Whats the linq+lambada expression to select all records in a table but only specific columns.
I tried something like the following which didnt work:
var Dc = new MyDataContext();
var mydata = Dc.TableA;
var newdata = mydata.Select(d => d (new {d.columnA,d.columnB,d.columnC}));
You were close - you have to project to an anonymous types with the columns you want:
var mydata = Dc.TableA.Select(d => new {d.columnA,d.columnB,d.columnC});
I think the issue you've got is a minor error in your code (in the example at least)
var Dc = new MyDataContext();
var mydata = Dc.TableA;
var newdata = mydata.Select(d => new {d.columnA,d.columnB,d.columnC});
var Dc = new MyDataContext();
var newdata = Dc.TableA.Select(d => new {d.columnA,d.columnB,d.columnC});

Get a list of documents from Mongo DB

I want to do something like this:
List<int> fff = new List<int>();
fff.Add(1);
fff.Add(2);
fff.Add(5);
Mongo m = new Mongo();
m.Connect();
var dataBase = m.GetDatabase("database");
var collection = dataBase.GetCollection("coll");
IMongoQuery queryable = collection.AsQueryable();
MongoQueryProvider prov = new MongoQueryProvider(collection);
var query = new MongoQuery(prov);
var ffppp = from p221 in query where fff.Contains((int)p221["oid"]) select p221;
This throws this error : The method 'Contains' could not be converted into a constant.
I saw that mongo has an operator $in. Does any one know how can I use it from c#? (http://www.mongodb.org/display/DOCS/Advanced+Queries)
Thanks
After some more google-ing, I found this:
http://www.claassen.net/geek/blog/2009/09/linq2mongodb-building-linq-provider-for.html
var mongo = new Mongo();
var queryable = mongo["db"]["collection"].AsQueryable();
var in = from d in queryable where d.Key("foo").In("bar", "baz") select d;

Categories

Resources