I am having trouble building a conditional query using C# MongoDB driver. Whenever I run the code below, I get an empty list. Any help will be greatly appreciated.
Here is my function
public async void searchBook()
{
Book book = new Book();
IMongoDatabase mdb = MongoDBConnectionManager.ConnectToMongoDB();
var query = new BsonDocument();
if (queryString.ContainsKey("Title"))
{
query.Add("Title", queryString["Title"]);
}
if (queryString.ContainsKey("ISBN"))
{
query.Add("Isbn", queryString["ISBN"]);
}
if (queryString.ContainsKey("Author"))
{
query.Add("Author", queryString["Author"]);
}
if (queryString.ContainsKey("Publisher"))
{
query.Add("Publisher", queryString["Publisher"]);
}
var collection = mdb.GetCollection<Book>("Book");
var sort = Builders<Book>.Sort.Ascending("Title");
if(query.ElementCount > 0)
{
var list = await collection.Find(query).Sort(sort).ToListAsync();
dt = ConvertToDataTable(list);
BindGridView(dt);
}
else
{
var list = await collection.Find(Builders<Book>.Filter.Empty).Sort(sort).ToListAsync();
dt = ConvertToDataTable(list);
BindGridView(dt);
}
}
You can use IMongoCollection to get your collection and then use AsQueryable
var query = collection.AsQueryable();
if (!string.IsNullOrEmpty(entity.Name))
query = query.Where(p => p.Name.Contains(entity.Name));
if (!string.IsNullOrEmpty(entity.Description))
query = query.Where(p => p.Description.Contains(entity.Description));
var YourList=query.ToList();
Related
I have following document in my MongoDB database:
{
"_id":1,
"user_name":"John Doe",
"addresses":[
{
"_id":null,
"geolocation":null,
"city":"Toronto"
},
{
"_id":null,
"geolocation":null,
"city":"Canada"
}
]
}
I want to create an index for the attribute addresses.city in my C# code so that I can do a text based search later. How can I achieve this?
By the way, I have implemented the following code to achieve this but it seems it doesn't work while running the query:
public void createIndexes() {
try {
var indexOptions = new CreateIndexOptions();
var indexKeys = Builders < Users> .IndexKeys.Text(_ => _.Addresses);
var indexModel = new CreateIndexModel < Users> (indexKeys, indexOptions);
var collection = _mongoDb.GetCollection < Users> ("users");
collection.Indexes.CreateOneAsync(indexModel);
} catch (Exception ex) {
throw;
}
}
The code executing the query:
//Creates connection with the mongodb
private MongoDbContext db = new MongoDbContext();
...
...
//Initializes the search term
string searchTerm = "Cana";
//Executes the query
var builder = Builders<Users>.Filter;
FilterDefinition<Users> filter;
filter = builder.Text(searchTerm);
var results = await db.Users.Find(filter).ToListAsync();
I'm using this MongoDB driver
I have a foreach with an ordebydescending(), but in one case I need to use an orderby() instead. Depending on the value of articleType how can I use an inline condition inside the foreach to allow this to happen.
This is the condition I need to build into to determine the use of orderbydescending or orderby
if (articleType == BusinessLogic.ArticleType.Webinar)
This is the full function
public static List<Article> GetArticles(BusinessLogic.ArticleType articleType, long languageID)
{
List<Article> articles = new List<Article>();
using (var db = new DatabaseConnection())
{
foreach (var record in db
.GetArticles(BusinessLogic.SystemComponentID, (int) articleType, languageID)
.OrderByDescending(c => c.Date_Time))
{
#region articleTextLanguageID
long articleTextLanguageID = GetArticleTextLanguageID(record.ID, languageID);
string previewImageName = GetArticle(record.ID, articleTextLanguageID).PreviewImageName;
#endregion
Article article = new Article()
{
ID = record.ID,
Title = record.Title,
Summary = record.Summary,
PreviewImageName = previewImageName,
Date = record.Date_Time,
ArticleTextLanguageID = articleTextLanguageID
};
articles.Add(article);
}
}
return articles;
}
Was thinking something along these lines, but its not working
foreach (var record in db
.GetArticles(BusinessLogic.SystemComponentID, (int)articleType, languageID)
.Where(articleType == BusinessLogic.ArticleType.Webinar.ToString()?.OrderByDescending(c => c.Date_Time)) : .OrderBy(c => c.Date_Time)))
The way to do this would be to construct the query in pieces. For example:
var query = db.GetArticles(BusinessLogic.SystemComponentID, (int)articleType, languageID);
if(articleType == BusinessLogic.ArticleType.Webinar)
{
query = query.OrderByDescending(c => c.Date_Time);
}
else
{
query = query.OrderBy(c => c.Date_Time);
}
foreach(var record in query)
{
// process
}
If you required additional sorting, you'd need an extra variable typed as IOrderedEnumerable/IOrderedQueryable (depending on what GetArticles returns) as an intermediate to chain ThenBy/ThemByDescending:
var source = db.GetArticles(BusinessLogic.SystemComponentID, (int)articleType, languageID);
IOrderedEnumerable<Article> query;
if(articleType == BusinessLogic.ArticleType.Webinar)
{
query = source.OrderByDescending(c => c.Date_Time);
}
else
{
query = source.OrderBy(c => c.Date_Time);
}
if(somethingElse)
{
query = query.ThenBy(c => c.OtherProperty);
}
foreach(var record in query)
{
// process
}
Based on your comment below, as notes above the second example would look more like the following (this means that db.GetArticles returns an IQueryable<Article> and not an IEnumerable<Article>):
var source = db.GetArticles(BusinessLogic.SystemComponentID, (int)articleType, languageID);
IOrderedQueryable<Article> query;
if(articleType == BusinessLogic.ArticleType.Webinar)
{
query = source.OrderByDescending(c => c.Date_Time);
}
else
{
query = source.OrderBy(c => c.Date_Time);
}
if(somethingElse)
query = query.ThenBy(c => c.OtherProperty);
foreach(var record in query)
{
// process
}
You could also shorten it to the following:
var source = db.GetArticles(BusinessLogic.SystemComponentID, (int)articleType, languageID);
var query = articleType == BusinessLogic.ArticleType.Webinar
? source.OrderByDescending(c => c.Date_Time)
: source.OrderBy(c => c.Date_Time);
if(somethingElse)
query = query.ThenBy(c => c.OtherProperty);
foreach(var record in query)
{
// process
}
I try to combine a projection and a distinct with the MongoDB driver but don't get anywhere...
I have:
var coll = db.GetCollection<Vat>(CommonConstants.VatCodeCollection);
// I like to combine in one statement:
var result = coll.Distinct<DateTime>("ValidSince", filter).ToList();
var projection = Builders<Vat>.Projection.Expression(x => new VatPeriod { ValidSince = x.ValidSince });
So at the end I like to get a List<VatPeriod> as a result of one statement. Of course I could do something like
var coll = db.GetCollection<Vat>(CommonConstants.VatCodeCollection);
List<VatPeriod> vatPeriods = null;
try
{
var result = coll.Distinct<DateTime>("ValidSince", filter).ToList();
if (result.Count > 0)
{
vatPeriods = new List<VatPeriod>(result.Count);
foreach (var dateTime in result)
{
vatPeriods.Add(new VatPeriod() {ValidSince = dateTime});
}
}
return vatPeriods;
}
catch .....
in my repository class, but I would prefer to do everything on the Mongo server. Any idea if and how this is possible?
I am trying to find all documents from a MongoDB database, which has the ObjectID from my list of IDs with C#. Here's what I'm trying:
public IEnumerable<Product> GetFromIDs(List<string> productIDs)
{
var client = new MongoClient(new MongoUrl("mongodb://localhost:27017"));
var db = client.GetDatabase("Database");
var products = db.GetCollection<Product>("Products")
.Find(x => x._id == productIDs)
.ToEnumerable();
return products;
}
productIDs is simply a list of ObjectIDs from the MongoDB database. Obviously trying to find by a list of IDs doesn't work that way, as it takes a single parameter.
How do I .Find() all the documents from my list of product IDs?
This is the strongly-typed way.
public IEnumerable<Product> GetFromIDs(List<string> productIDs)
{
var client = new MongoClient(new MongoUrl("mongodb://localhost:27017"));
var db = client.GetDatabase("Database");
var productsCollection = db.GetCollection<Product>("Products");
var productObjectIDs = productIDs.Select(id => new ObjectId(id));
var filter = Builders<Product>.Filter
.In(p => p.Id, productObjectIDs);
var products = productsCollection
.Find(filter)
.ToEnumerable();
return products;
}
I figured out a pretty hacky solution. Not one of my proudest moments to be honest:
ObjectId[] allIDs = new ObjectId[productIDs.Count];
for(var i = 0; i < productIDs.Count; i++)
{
allIDs[i] = new ObjectId(productIDs[i]);
}
var filter = new BsonDocument("_id", new BsonDocument("$in", new BsonArray(allIDs)));
var products = db.GetCollection<Product>("Products").Find(filter).ToEnumerable();
But hey, it works.
first time i'm using MongoDB.
I have read this example:
SELECT a,b FROM users WHERE age=33
db.users.find({age:33}, {a:1,b:1})
But I can't translate it into C#. Can anyone help me?
I have translated your query below using the new C# driver (2.2)
var mongoClient = new MongoClient(""mongodb://127.0.0.1:27017"");
var database = mongoClient.GetDatabase("databaseName");
IMongoCollection<Users> _collection = database.GetCollection<Users>("Users");
var condition = Builders<Users>.Filter.Eq(p => p.age, 33);
var fields = Builders<Users>.Projection.Include(p => p.a).Include(p => p.b);
var results= _collection.Find(condition).Project<Users>(fields).ToList().AsQueryable();
You can do it using SetFields method of MongoCursor class, below full example:
var server = MongoServer.Create(connectionString);
var db = _server.GetDatabase("dbName");
var users = db.GetCollection("users");
var cursor = users.FindAs<DocType>(Query.EQ("age", 33));
cursor.SetFields(Fields.Include("a", "b"));
var items = cursor.ToList();
you can use anonymous class
public class User
{
public int age;
public string a;
public string b;
}
var collection = db.GetCollection<User>("Users");
var results = collection.Find(Builders<User>.Filter.Eq(user => user.age, 33))
.Project(u => new { u.a, u.b }).ToList();
//create user class
//(not sure how your class looks like)
public class User
{
public int age;
public string a;
public string b;
}
//then you can use LINQ easily
var server = MongoServer.Create(connectionString);
var db = server.GetDatabase("dbName");
var usersCollection = db.GetCollection<User>("users");
var filteredCollection = usersCollection.AsQueryable().Where(x=> x.age < 33).Where(x=> x.a != null).Contains(x=> x.b != null);