MongoDB C# Query Select specific keys from document - mongodb

How can i do this from c# mongoDb drivers.
sql query :SELECT a,b FROM users
mondb javascript query : db.users.find({}, {a:1,b:1})

How about this:
var database = MongoDatabase.Create(connectionString);
var userCollection = database.GetCollection<Exercise>("users");
var users = userCollection.Find().SetFields("a", "b");
If I understand your question correctly .SetFields does what you want.

Related

MongoDB query in C#

I'd like to get certain documents that match a specific clause, but don't know how to achieve that WHERE effect in relational databases. I have a simple database with words and their translations (objects with 2 fields) and use this code
var words = database.GetCollection<Word>("Dictionary")
to get them. But this gets the whole collection. What if there were thousands of records in the collection? How to get just the records I want?
Use regular expressions matching as below. The 'i' shows case insensitivity.
var collections = mongoDatabase.GetCollection("Abcd");
var queryA = Query.And(
Query.Matches("strName", new BsonRegularExpression("ABCD", "i")),
Query.Matches("strVal", new BsonRegularExpression("4121", "i")));
var queryB = Query.Or(
Query.Matches("strName", new BsonRegularExpression("ABCD","i")),
Query.Matches("strVal", new BsonRegularExpression("33156", "i")));
var getA = collections.Find(queryA);
var getB = collections.Find(queryB);
For Using 'And' or 'Or' in your query, if you want to search over multiple fields.
This assumes you have a class called Word that is modled like you collection.
MongoServer _server = new MongoClient(connectionString).GetServer();
MongoDatabase _database = _server.GetDatabase(database);
MongoCollection _collection = _database.GetCollection(collection);
var results = _collection.FindAs<Word>(Query.EQ("MyField","WordToFind"));

Porting query from JPQL to mongo using spring data mongo Criteria

I've ported some of my Entity from JPA to document and now porting some of my queries.
here is the JPA query:
em.createQuery("select distinct c from CustomerImpl c left join fetch c.addresses ca where (:name is null or c.firstName LIKE :name or c.lastName LIKE :name) and (:ref is null or c.externalReference LIKE :ref) and (:city is null or ca.city LIKE :city) order by c.firstName").setParameter("name", name).setParameter("ref", customerRef).setParameter("city", city).getResultList();
below is my attempt :
Criteria orNameCriteria = new Criteria().orOperator(Criteria.where("firstName").is(null), Criteria.where("firstName").is(name), Criteria.where("lastName").is(name));
Criteria orCustomerRefCriteria = new Criteria().orOperator(Criteria.where("externalReference").is(null), Criteria.where("externalReference").regex(customerRef,"i"));
Criteria orAddress = new Criteria().orOperator(Criteria.where("addresses.city").is(null), Criteria.where("addresses.city").regex(city, "i"));
Query nameq = new Query(new Criteria().andOperator(orNameCriteria,orCustomerRefCriteria,orAddress));
this query return zero size arraylist. I've then changed the orNameCriteria to use is clause and making sure the data contained in name variable has / as suffix and prefix. That didn't work as well.
but queries from mongoVue and RockMongo clients :
{ firstName: /SAM/}
returns data.
Question 1: How do you write LIKE CLAUSE with spring-data-mongo Criteria?
Question 2 : is that the right way to use or and and clause with criteria
Thanks for reading
Criteria.where("field").regex(pattern) should work
Since I don't have the ability add comments...
If you do a static import on Criteria, it will make your where clauses look a lot better.
Criteria orAddress = new Criteria().orOperator(where("addresses.city").is(null), where("addresses.city").regex(city, "i"));

MongoDB C# Query for 'NotLike' on string

I'm using official Mongo C# driver. As suggested in answer to one question I'm using the following for the 'like' operator -
Query.Matches("name", "Joe");
My question is how can I achieve the 'NotLike' functionality ?
Assuming you are using the new Query builder in version 1.5, you would do it this way:
var query = Query.Not(Query.Matches("name", "Joe"));
In version 1.5 we also introduced a new typed Query builder, which you could use this way:
var query = Query.Not(Query<C>.Matches(x => x.Name, "Joe"));
Finally, you could also write a LINQ query:
var query = collection.AsQueryable<C>().Where(x => !Regex.IsMatch(x.Name, "Joe"));

How to use mongo database queries?

I am using MongoDb for my c sharp project instead of mysql, now i want to use query like select * from student Where (name is null or name='XXX') and (sno is null or sno=10), how can i build this query in mongodb.
thanks,
#dinnu.
This should get you started:
var mongoServer = MongoDB.Driver.MongoServer.Create("mongodb://localhost?safe=true");
var mongoDatabase = mongoServer.GetDatabase("test");
var mongoCollection = mongoDatabase.GetCollection<TModel>("Test");
var cursor = mongoCollection.Find(Query.And(
Query.Or(
Query.EQ("Name", "xxx"),
Query.EQ("Name", null)),
Query.Or(
Query.EQ("sno", 10)),
Query.EQ("sno", null)));
Where TModel is the type of the class you want to deserialize from the db. Now you can use cursor to iterate the results of that query, for example:
var someModel = cursor.FirstOrDefault();
Take a look at Fluent Mongo (https://github.com/craiggwilson/fluent-mongo). It adds Linq on top of the official 10gen driver. Thus far I have found using it to be a good experience. It is available via the Nuget or the GitHub.

MongoDb: how to return distinct field in select (find) with C# official driver

I need to select User Name from the collection of Users. I do it in a such way:
MongoCollection<Enums> coll = Db.GetCollection<Enums>("Users");
var query = Query.EQ("_id", id);
var res = coll.FindOne(query);
var name = res.Name;
var url = res.UserUrl; //or some more fields, not just Name
Assuming that User document can contain a lot of data, and there is no need to transfer the whole user document, how to select only a few distinct fields, using official C# driver?
You'll have to use a function that returns a MongoCursor.
In the MongoCursor you can specify the fields you want to return.
var result = Db.GetCollection<Enums>("Users").FindAll();
result.Fields = Fields.Include(new [] {"Name"});;
foreach (var user in result)
{
Console.WriteLine(user.Name);
}