Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying a subfield in documentdb

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.

like image 795
Sid Avatar asked Dec 09 '25 01:12

Sid


1 Answers

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

like image 187
mickl Avatar answered Dec 10 '25 13:12

mickl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!