Querying a subfield in documentdb

久未见 提交于 2019-12-02 02:38:57

问题


For example I have a document below for collection = delivery:

{
    "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
}

is it possible to do a search with "deliverynum" = 999 and the output would be like below?

{
    "doc": [        
        {
            "docid": "17",
            "deliverynum": "999",
            "text": "txxxxxx",
            "date": "2019-07-18T12:37:58Z"
        }
    ],
    "id": "123",
    "cancelled": false
}

or should I make another Collection just for the Doc part?

I am having trouble making a query in C# for this kind of scenario.


回答1:


In Mongo shell you can use the $(projection) operator:

db.collection.find({ "doc.deliverynum": "999" }, { "doc.$": 1 })

Corresponding C# code can look like below:

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();

You can also use q = Builders<Model>.Filter.Empty if you want to get all documents even if the don't contain deliverynum =``999



来源:https://stackoverflow.com/questions/57096251/querying-a-subfield-in-documentdb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!