[CDRIVER-2111] MongoDB C driver how to find object field value in array of objects Created: 03/Apr/17  Updated: 11/Sep/19  Resolved: 03/Apr/17

Status: Closed
Project: C Driver
Component/s: libmongoc
Affects Version/s: 1.6.0
Fix Version/s: None

Type: Task Priority: Minor - P4
Reporter: eh.y Assignee: Unassigned
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Hi. everyone.

Query for a field in an object in array with Mongo?
i have this json and i want check if the value of sessions.id == 1234556:

{
    "_id": ObjectId("5768e43"),
    "APPID": {
        "Number": 0,
    },
    sessions: [
        {
            id:1234556,
            "setOID": {
                "Number": 0 
 
            },
            "custID": {
                "Number": 0 
            },
        },
        {
            id:133333,
            "setOID": {
                "Number": 2 
            },
            "custID": {
                "Number": 2 
            },
        },
     ]
}
 
query = BCON_NEW ("$query", "{", "session.id", 1234556,"}");
cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);
 
 the result is like this:
 
{
    "_id": ObjectId("5768e43"),
    "APPID": {
        "Number": 0,
    },
    sessions: [
        {
            id:1234556,
            "setOID": {
                "Number": 0 
 
            },
            "custID": {
                "Number": 0 
            },
        },
        {
            id:133333,
            "setOID": {
                "Number": 2 
            },
            "custID": {
                "Number": 2 
            },
        },
     ]
}
 
but I want this result.
 
{
    "_id": ObjectId("5768e43"),
    "APPID": {
        "Number": 0,
    },
    sessions: [
        {
            id:1234556,
            "setOID": {
                "Number": 0 
 
            },
            "custID": {
                "Number": 0 
            },
        }
     ]
}



 Comments   
Comment by A. Jesse Jiryu Davis [ 03/Apr/17 ]

The C Driver has no specific feature for selecting a subdocument from an array. You can retrieve only the portion of the document you want from MongoDB with an aggregation pipeline. I'll show you in shell syntax:

db.collection.aggregate({
  $match: {
    "sessions.id": 1234556
  }
}, {
  $unwind: "$sessions"
}, {
  $match: {
    "sessions.id": 1234556
  }
})

I'll leave it to you to translate this to C.

Generated at Wed Feb 07 21:14:12 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.