Thursday, June 9, 2011

MongoDB C# Driver, Query multiple tags that are required

Tried hard to find the solution to querying multiple tags through the MongoDB C# driver.
Many of the solutions that I found were about using OR to put together the tags but I needed to AND the tags. I.e. all tags supplied were required to be present on in the result.
The solution was quite simple actually. Just my mind that thought it would require some special solution.
string[] tags = new string[] {"foo", "bar"};
var sort = SortBy.Descending("created");
var query = MongoDB.Driver.Builders.Query.All("tags", BsonArray.Create(tags));
var dbPages = pages.Find(query)
.SetSortOrder(sort)
.SetLimit(limit)
.SetSkip(offset);

  1. Create a string array with the tags that you want to query with
  2. Add sorting if needed
  3. Call MongoDB.Driver.Builders.Query to build your query
  4. Use find on your MongoCollection together with your query.
  5. Add Limit and Offset if needed.
Enjoy : )

No comments:

Post a Comment