0

Suppose I have following collection :

{    _id" : ObjectId("4f1d8132595bb0e4830d15cc"), 
    "Data" : "[
            { "id1": "100002997235643", "from": {"name": "Joannah" ,"id": "100002997235643"} , "label" : "test"  } , 
            { "id1": "100002997235644", "from": {"name": "Jon" ,"id": "100002997235644"} , "label" : "test1"  } 
        ]" , 
    "stat" : "true" 
}

How can I retrieve id1 , name , id ,label or any other element?

I am able to get _id field , DATA (complete array) but not the inner elements in DATA.

RAS
  • 8,100
  • 16
  • 64
  • 86
Pradeep Bhadani
  • 4,435
  • 6
  • 29
  • 48

2 Answers2

0

You cannot query for embedded structures. You always query for top level documents. If you want to query for individual elements from your array you will have to make those element top level documents (so, put them in their own collection) and maintain an array of _ids in this document.

That said, unless the array becomes very large it's almost always more efficient to simply grab your entire document and find the appropriate element in your app.

Remon van Vliet
  • 18,365
  • 3
  • 52
  • 57
0

I don't think you can do that. It is explained here.

If you want to access specific fields, then following MongoDB Documentation, you could add a flag parameter to your query, but you should redesign your documents for this to be useful:

Field Selection

In addition to the query expression, MongoDB queries can take some additional arguments. For example, it's possible to request only certain fields be returned. If we just wanted the social security numbers of users with the last name of 'Smith,' then from the shell we could issue this query:

// retrieve ssn field for documents where last_name == 'Smith':
db.users.find({last_name: 'Smith'}, {'ssn': 1});

// retrieve all fields *except* the thumbnail field, for all documents:
db.users.find({}, {thumbnail:0});
Community
  • 1
  • 1
spike
  • 89
  • 4