简体   繁体   English

如何在 MongoDB C# 驱动程序中按字段值范围选择文档?

[英]How to select documents by field range of values in MongoDB C# driver?

I have a collection named Items.我有一个名为 Items 的集合。 Documents in the Items collection have a field named "LocationId." Items 集合中的文档有一个名为“LocationId”的字段。 How do I select, and bring back to server, all Item documents that have a LocationId that matches a list, array, etc (whatever collection you prefer) of Location Ids?如何选择所有具有与位置 ID 的列表、数组等(您喜欢的任何集合)匹配的 LocationId 的 Item 文档并将其带回服务器?

tl:dr for clarity: tl:dr 为清楚起见:
1. Have Items collection. 1.有物品收藏。
2. Have list of LocationIds, eg "1, 5, 6, 12, 99" on the server. 2. 在服务器上有 LocationIds 列表,例如“1, 5, 6, 12, 99”。
3. Need to bring back all Item documents that have a LocationId listed in the collection. 3. 需要带回集合中列出了 LocationId 的所有 Item 文档。

You can build simple queries using lambda expression, MongoDB.Driver supports it您可以使用 lambda 表达式构建简单的查询,MongoDB.Driver 支持它

var collection = database.GetCollection<Item>("Item");
var list = await collection.Find(x => locationIds.Contains(x.LocationId)).ToListAsync();

I was given this solution, which works with the older driver:我得到了这个解决方案,它适用于较旧的驱动程序:

 var locations = new BsonValue[] { 1, 2, 3, 4 };
 var collection = database.GetCollection<Item>("Item");
 var data = collection
            .Find(Builders<BsonDocument>.Filter.In("LocationId", locations))
            .Project(x => Mapper.Map<BsonDocument, ItemViewModel>(x))
            .ToListAsync().Result;

The funny thing is that I don't know what "new BsonValue[]{}" does.有趣的是,我不知道“new BsonValue[]{}”是做什么的。 Guess is bson array.猜猜是bson数组。

here's an alternate way using builders/filters.这是使用构建器/过滤器的另一种方法。

var ids = new List<Int32> { 1, 2, 3, 4, 5, 6 };
var filter = Builders<Item>.Filter.AnyIn("LocationId", ids);
var collection = database.GetCollection<Item>("Item");
var results = await collection.FindAsync(filter);

var locations = await results.ToListAsync();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM