. NET under the operation of MongoDB (ii)

Source: Internet
Author: User

This time, the use of C#driver, MongoDB for a simple query.

We can use the static method in the query class to create a series of queries to achieve the purpose of the query.

Query is in the using MongoDB.Driver.Builders namespace.

1. Single condition query, you can refer to the following code:

            var query = Query.eq ("ColName", "Value");            foreach (Bsondocument doc in collection. Find (query)            {                Debug.WriteLine (doc["colname"). ToString () + "\ t");            }

2. To make a combination of conditions, such as and, or or, refer to the code:

            var query = query.or (                query.eq ("ColName1", "Value1"),                query.eq ("ColName2", "Value2")                );            foreach (Bsondocument doc in Dotnetcollection.find (query))            {                Debug.WriteLine (doc["ColName1"]. ToString () + "\ T" +         doc["ColName2"]. ToString ());            }        

Using these QueryBuilder to create a query is a recommended method for MongoDB, simple and clear.

3. To return the specified object, you can refer to the code:

            var query = Query<table1>. EQ (b = b.testcol1, "BBB");            foreach (table1 ele in dotnetcollection.findas<table1> (query))            {                Debug.WriteLine (ele.testcol1 + "\ T") + ele.testcol2);            }

where table1 is defined as:

        public class table1        {public            ObjectId _id {get; set;}            public string TestCol1 {get; set;}            public string TestCol2 {get; set;}        }

It is important to note that _id must contain this attribute, ObjectId is MongoDB.Bson.ObjectId, otherwise it will produce "Element ' _id ' does not match any field or property in the data reading. Class "This error.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.