How to write a multi-element query in MongoDb and C #?

In our Mongo database, we have a collection indexed by "StoreId" and "ItemId". The following query returns all combinations of merchandise stores (total 9 documents) included in list "B".

var productQuery = Query.In("ItemId", new BsonArray(new List<int> {1, 2, 3})); var storeQuery = Query.In("StoreId", new BsonArray(new List<int> {1, 2, 3})); var queryToBringNineDocuments = Query.And(productQuery, storeQuery); 

How to write a query that returns documents with keys to the following list of element tuples?

 var neededProductStores = new List<Tuple<int, int>> { new Tuple<int, int>(1, 2), new Tuple<int, int>(1, 3), new Tuple<int, int>(2, 1), new Tuple<int, int>(3, 2) }; var queryToBringFourDocuments = ?; 
+4
source share
2 answers

It seems to me that currently there is only one way - to create an additional field that will contain both identifiers and a request on it

So, in your C # class, which you store in the database, you can:

 public string ProductStoreId { get { return string.Format("{0}_{1}",ItemId, StoreId); } set { } //empty set means that it will be stored to database } 

Then your request will look like this:

 var query = Query.In("ProductStoreId", new BsonArray(new List<string> {"1_2", "1_3",.. })); 
+4
source

This can also be done using the OR query, which accumulates I-queries. It can get pretty ugly if you have many combinations.

 var neededProductStores = new List<Tuple<int, int>> { new Tuple<int, int>(1, 2), new Tuple<int, int>(1, 3), new Tuple<int, int>(2, 1), new Tuple<int, int>(3, 2) }; IMongoQuery[] queries =(from t in neededProductStores select Query.And(Query.EQ("ItemId", t.Item1), Query.EQ("StoreId", t.Item2))).ToArray<IMongoQuery>(); var queryToBringFourDocuments = Query.Or(queries); 
+1
source

Source: https://habr.com/ru/post/1401402/


All Articles