2

I have a json data structure as follow:

 "_id" : {
           Inst_Id: 1119689706
          },
 "items" : [
     {
        "Token" : "Let", 
        "Lemma" : "let", 
        "POS" : "VERB"
     },
     {
        "Token" : "'s", 
        "Lemma" : "-PRON-", 
        "POS" : "PRON" 
     },       
        {
         "Token" : "face", 
          "Lemma" : "face", 
          "POS" : "VERB"
         },
         {
          "Token" : "it", 
          "Lemma" : "-PRON-", 
          "POS" : "PRON", 
         }
          ]

My items are basically fields which have arrays of token of sentences (e.g. "Let's face it inside.) How can I search for 2 or more criteria inside the same item of an array? I have tried $elemMatch but it only matches elements across arrays and not inside one array. For example, I want to look for a sentence for which the token is "face" AND the POS is "VERB" at the same time.

Fasa
  • 57
  • 2
  • 9
  • just to clarify: what's the expected output for face+VERB ? – mickl Jul 17 '18 at 06:10
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – Ashh Jul 17 '18 at 06:44

2 Answers2

0

$elemMatch is the way :

db['01'].find(
    {items:{$elemMatch:{Token:"face",POS:"VERB"}}}        
)

will return whole document. To return only matching array elements, add the same to projection part of query :

db['01'].find(
    {items:{$elemMatch:{Token:"face",POS:"VERB"}}}, 
    {items:{$elemMatch:{Token:"face",POS:"VERB"}}}
)

will return

    { 
    "_id" : {
        "Inst_Id" : 1119689706.0
    }, 
    "items" : [
        {
            "Token" : "face", 
            "Lemma" : "face", 
            "POS" : "VERB"
        }
    ]
}
matthPen
  • 4,253
  • 1
  • 16
  • 16
  • Thank you. I didn't know we can do an $elemMatch with two or more elements. Wonderful! – Fasa Jul 17 '18 at 06:42
0

According to description as mentioned into above question, as a solution to it,please try executing following MongoDB query

    db.getCollection("test").find({
    items: {
        $elemMatch: {
            Token: 'face',
            "POS": "VERB"
        }
    }
}, {
    'items.$': 1
})
Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26