英文:
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']}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论