4.2 数组查询
老规矩,先添加数据
var documents = new[]
{
new BsonDocument
{
{ "item", "journal" },
{ "qty", 25 },
{ "tags", new BsonArray { "blank", "red" } },
{ "dim_cm", new BsonArray { 14, 21 } }
},
new BsonDocument
{
{ "item", "notebook" },
{ "qty", 50 },
{ "tags", new BsonArray { "red", "blank" } },
{ "dim_cm", new BsonArray { 14, 21 } }
},
new BsonDocument
{
{ "item", "paper" },
{ "qty", 100 },
{ "tags", new BsonArray { "red", "blank", "plain" } },
{ "dim_cm", new BsonArray { 14, 21 } }
},
new BsonDocument
{
{ "item", "planner" },
{ "qty", 75 },
{ "tags", new BsonArray { "blank", "red" } },
{ "dim_cm", new BsonArray { 22.85, 30 } }
},
new BsonDocument
{
{ "item", "postcard" },
{ "qty", 45 },
{ "tags", new BsonArray { "blue" } },
{ "dim_cm", new BsonArray { 10, 15.25 } }
}
};
collection.InsertMany(documents);
匹配整个数组
//语法
Builders<BsonDocument>.Filter.Eq(<field>, <value>)
//实例
var filter = Builders<BsonDocument>.Filter.Eq("tags", new[] { "red", "blank" });
var result = collection.Find(filter).ToList();
//匹配的时候是完全匹配,包括顺序
//但是有时候你希望查询包含了red和blank两个元素,而且不考虑先后顺序,那么使用all 操作符
eg:
var filter = Builders<BsonDocument>.Filter.All("tags", new[] { "red", "blank" });
var result = collection.Find(filter).ToList();
查询数组中的一个元素
//语法
Builders<BsonDocument>.Filter.Eq(<field>, <value>)
//实例
var filter = Builders<BsonDocument>.Filter.Eq("tags", "red");
var result = collection.Find(filter).ToList();
//使用查询操作符 语法
var builder = Builders<BsonDocument>.Filter;
builder.And(builder.Eq(<array field>, <value1>), builder.Lt(<array field>, <value2>));
//实例
var filter = Builders<BsonDocument>.Filter.Gt("dim_cm", 25);
var result = collection.Find(filter).ToList();
多个条件查询数组
//使用混合过滤条件
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Gt("dim_cm", 15), builder.Lt("dim_cm", 20));
var result = collection.Find(filter).ToList();
//使用 $elemMatch operator
var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("dim_cm", new BsonDocument { { "$gt", 22 }, { "$lt", 30 } });
var result = collection.Find(filter).ToList();
参考地址:https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#op._S_elemMatch
依靠数组位置查询元素
var filter = Builders<BsonDocument>.Filter.Gt("dim_cm.1", 25);
var result = collection.Find(filter).ToList();
查询数组的长度
var filter = Builders<BsonDocument>.Filter.Size("tags", 3);
var result = collection.Find(filter).ToList();
顶
收藏
关注
评论
作者:王思明
出处:http://www.cnblogs.com/maanshancss/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。所有源码遵循Apache协议,使用必须添加 from maanshancss
出处:http://www.cnblogs.com/maanshancss/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。所有源码遵循Apache协议,使用必须添加 from maanshancss