0

In my nodejs application, I want to find items matching labels.

I have an object with labels:

{
    "name": "object1",
    "labels": [
        {"name": "label1"},
        {"name": "label2"}
    }
}

From this collection, I want to find all items matching the labels the user provides. (/api/findLabels/label1,label2)

At this point, I know I can find this in MongoDB with this query:

db.getCollection('items')
    .find(
        {'labels': {
            $elemMatch: 
                {'name': 'label1', 'name': 'label2'}
        }}

However, I seem to be having issues with building the query in Node.js.

At this point, I have:

Item.find(
    {
        'labels':
        {
            $elemMatch: labels
        }
    }).exec(function(err, items){
        ...
    })

But how can I build the correct structure for the labels parameter? Setting a key more than once with a new value is just replacing the value, not adding it to the list, which makes sense.

Any ideas?

stijnpiron
  • 359
  • 2
  • 4
  • 15
  • @neil-lunn Can you verify if my question is still a duplicate with the added info? I have no issues with building the correct MongoDB query, I have issues with building it in my Node.JS app... – stijnpiron Jun 27 '17 at 10:53
  • Of course I can verify. Multiple answers there showing use of `.aggregate()` and the `$filter` operator. That is how you return "multiple" matched items from an array. – Neil Lunn Jun 27 '17 at 10:54
  • Why don't you use normal query using *find()*, I don't think you need `$elemMatch`. something like this might work: `{ "labels.name": { $in: ["label1","label2"] } }` – Naga Penmetsa Jun 27 '17 at 11:22

0 Answers0