Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find a single tag in a mongodb query

I want to fetch tags that only contains ‘black’, But when I run the query I get tags that contains black and some other color. How can I get tags that contains only black?.

Here is what I tried

const express = require('express');
const Inventory = require('../models/inventory');
const router = express.Router();

router.get('/inventory2', async (req, res) => {

  const inventory = await Inventory.find({
    tags: 'black',
  });
 
  res.send(inventory);
});

Here is what I was expecting

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
 {
    size: { h: 22, w: 30.5, uom: 'cm' },
    _id: new ObjectId("643cda1ccfda6cc57d5948ba"),
    item: 'table',
    qty: 851,
    tags: [ 'black' ],
    status: 'D'
 }
]

Here is what I got:

[
  {
    size: { h: 14, w: 21, uom: 'cm' },
    _id: new ObjectId("643cd5ef705862daba5fa9e7"),
    item: 'journal',
    qty: 25,
    tags: [ 'black', 'red' ],
    status: 'A',
    __v: 0
  },
  {
    size: { h: 22, w: 30.5, uom: 'cm' },
    _id: new ObjectId("643cda1ccfda6cc57d5948ba"),
    item: 'table',
    qty: 851,
    tags: [ 'black' ],
    status: 'D'
  }
]

>Solution :

You can add query for size so it will fetch the tags that have only specified size that will be 1

const inventory = await Inventory.find({
    tags: 'black',
    tags: {$size : 1}
  });

or you can exclude other colors also

const inventory = await Inventory.find({
    tags: 'black',
    tags: {$nin: ['red', 'green']}
  });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading