在MongoDB查询中查找单个标签。

huangapple go评论56阅读模式
英文:

find a single tag in a mongodb query

问题

我想获取仅包含 'black' 的标签,但运行查询时,我得到了包含黑色和其他一些颜色的标签。我该如何获取仅包含黑色的标签?

这是我尝试过的:

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);
});

这是我期望的结果:

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

这是我得到的结果:

[
  {
    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'
  }
]
英文:

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

[
 {
    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'
  }
]

答案1

得分: 1

你可以添加查询以获取指定大小的标签,大小为1

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

或者你可以排除其他颜色

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

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']}
  });

huangapple
  • 本文由 发表于 2023年4月17日 14:07:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76032112.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定