例如,我下面有一个用于收集=交货的文档:
{
"doc": [
{
"docid": "15",
"deliverynum": "123",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
},
{
"docid": "16",
"deliverynum": "456",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
},
{
"docid": "17",
"deliverynum": "999",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
}
],
"id": "123",
"cancelled": false
}
是否可以使用“ deliverynum” = 999进行搜索,并且输出如下所示?
{
"doc": [
{
"docid": "17",
"deliverynum": "999",
"text": "txxxxxx",
"date": "2019-07-18T12:37:58Z"
}
],
"id": "123",
"cancelled": false
}
还是我应该为文档部分创建另一个收藏集?
在这种情况下,我很难用C#进行查询。
答案 0 :(得分:2)
在Mongo shell中,您可以使用$(projection)运算符:
db.collection.find({ "doc.deliverynum": "999" }, { "doc.$": 1 })
对应的C#代码如下所示:
var q = Builders<Model>.Filter.ElemMatch(x => x.doc, d => d.deliverynum == "999");
var p = Builders<Model>.Projection.ElemMatch(x => x.doc, d => d.deliverynum == "999");
var data = Col.Find(q).Project(p).ToList();
即使您要获取所有文档,即使其中不包含q = Builders<Model>.Filter.Empty
,也可以使用deliverynum =``999