0

I have this arbitrary structure of a collection. Need to find a match on itemId. Here's the structure:

{
    "_id" : "uHof564CDJcnvFHKz",
    "user_id" : "dukcCKjFcQe2v7bHD",
    "cart" : {
        "createdAt" : ISODate("2016-04-19T18:12:52.456Z"),
        "items" : [ 
            {
                "itemId" : "FfK49XAcX7YR",
                "itemPrice" : "10",
                "shortName" : "Item Description",
                "itemType" : "item1"
            },
             {
                "itemId" : "RgX6FfuK49XAcX",
                "itemPrice" : "20",
                "shortName" : "Item Description",
                "itemType" : "item2"
            }         
        ]
    }

So, I have an itemId and need to find a match in "cart -- items".

I tried $elemMatch, and multiple $elemMatch that did not work, returned null.

Florida G.
  • 269
  • 3
  • 11
  • Please a sample document as it appears in the `mongo` shell. It's pretty unclear as to what the actual structure as you have represented it actually is, and could be interpreted in different ways. – Neil Lunn Apr 20 '16 at 02:15
  • Added a screenshot. Thanks! – Florida G. Apr 20 '16 at 02:26
  • I really wish you would discover the "text" mode in your robomongo and **not** post screenshots ( Grr! my eyes! ). So what are you actually asking for? Matching a specific value in `"cart.items"`? Or something else? Because your question "looks like this one": [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – Neil Lunn Apr 20 '16 at 02:47
  • Using this link, this query .find({"items.itemId":"RgX6FfuK49XAcX7YR"},{_id: 0, items: {$elemMatch: {itemId: "RgX6FfuK49XAcX7YR"}}}) does not find a record. – Florida G. Apr 20 '16 at 03:13
  • Because it's just `.find({"cart.items.itemId": "RgX6FfuK49XAcX7YR" },{ "cart.items.$": 1 })`. You missed the "cart", which is the object containing the field. – Neil Lunn Apr 20 '16 at 03:15
  • Yep, that worked. Thanks. Could you post the answer so I could accept it? – Florida G. Apr 20 '16 at 03:21
  • Question is a basically a duplicate and marked as such. The missing `"cart"` part is also quite scarily "another" duplicate question, since it seems to be commonly missed to specify the whole path. – Neil Lunn Apr 20 '16 at 03:25

0 Answers0