I have a products table with below schema
(ProductID INT, ProductStartDate date, ProductExpDate date,
ProductTypeID int, #PacketsInProduct int,
Price int, Discount int, Score int)
I need to write a query something like this in MongoDB. I am using C# driver 1.5. The problem I am getting in first CTE below (Products_CTE) where Row_NUMBER() is deciding the product rank which is matching my where conditions, based on the rank I need to filter the rows in 2nd CTE. All my where conditions are dynamic, Can anyone help me out here. Thanks in advance
;WITH Products_CTE
AS
(
SELECT
ROW_NUMBER() OVER(PARTITION BY ProductID ORDER BY Score Desc, Price Asc) as RankByProduct,
*
FROM Products
WHERE
ProductID IN (1,2,3)
AND ProductTypeID IN (001,002)
AND [#PacketsInProduct] >3 and [#PacketsInProduct] <10
and ProductExpDate < GETDATE()
),
Products2_CTE
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY Score DESC, Price ASC) as rownum,
*
FROM Products_CTE
WHERE RankByProduct <= 3
)
SELECT
*
from Products2_CTE cte1
where rownum BETWEEN 15 AND 25
ORDER BY [Score] DESC, [Price] ASC
This query is going to require you building a map/reduce. Check to docs here: http://www.mongodb.org/display/DOCS/MapReduce.
If you need some help constructing the map/reduce, let me know and I’ll do my best. I’d encourage you to try it yourself first though. Note that map/reduce isn’t for real time querying, so you’ll need to snapshot the results, which means you are working with eventually consistent data and the business needs to know about it and be ok with it.
Furthermore, chances are that your schema could be optimized for this type of query depending on your needs. Storing data in mongodb the same way you store it in a relational database is almost never the right choice. If it is the right choice, then chances are you should stick with a relational model anyways.