4.1 MongDB基础-查询子文档
老规矩,先添加数据
var documents = new[]
{
new BsonDocument
{
{ "item", "journal" },
{ "qty", 25 },
{ "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } } },
{ "status", "A" }
},
new BsonDocument
{
{ "item", "notebook" },
{ "qty", 50 },
{ "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
{ "status", "A" }
},
new BsonDocument
{
{ "item", "paper" },
{ "qty", 100 },
{ "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
{ "status", "D" }
},
new BsonDocument
{
{ "item", "planner" },
{ "qty", 75 },
{ "size", new BsonDocument { { "h", 22.85 }, { "w", 30 }, { "uom", "cm" } } },
{ "status", "D" }
},
new BsonDocument
{
{ "item", "postcard" },
{ "qty", 45 },
{ "size", new BsonDocument { { "h", 10 }, { "w", 15.25 }, { "uom", "cm" } } },
{ "status", "A" } },
};
collection.InsertMany(documents);
匹配整个子文档
//语法
Builders<BsonDocument>.Filter.Eq(<field>, <value>)
// 实例
var filter = Builders<BsonDocument>.Filter.Eq("size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } });
var result = collection.Find(filter).ToList();
//必须全部相同
指定匹配子文档中的某个字段
var filter = Builders<BsonDocument>.Filter.Eq("size.uom", "in");
var result = collection.Find(filter).ToList();
使用查询操作符匹配
//例子
var builder = Builders<BsonDocument>.Filter;
builder.And(builder.Eq(<field1>, <value1>), builder.Lt(<field2>, <value2>));
//语法
var filter = Builders<BsonDocument>.Filter.Lt("size.h", 15);
var result = collection.Find(filter).ToList();
指定 And 条件
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Lt("size.h", 15), builder.Eq("size.uom", "in"), builder.Eq("status", "D"));
var result = collection.Find(filter).ToList();
顶
收藏
关注
评论
作者:王思明
出处:http://www.cnblogs.com/maanshancss/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。所有源码遵循Apache协议,使用必须添加 from maanshancss
出处:http://www.cnblogs.com/maanshancss/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。所有源码遵循Apache协议,使用必须添加 from maanshancss