Sid
Sid

Reputation: 765

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.

Upvotes: 3

Views: 507

Answers (1)

mickl
mickl

Reputation: 49945

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

Upvotes: 4

Related Questions