我是 MongoDB 的新手。我想找到对象值来查找集合。
以下是合集:
语言:
{
_id: 15,
language:English,
status: Active
},
{
_id: 20,
language:Spanish,
status: Active
},
类别:
这15, 20
是name
对象中的语言 ID
{
_id: 1,
name: {
15: Office,
20: Oficina
},
status: Active
},
{
_id: 2,
name: {
15: Restaurant,
20: Restaurante
},
status: Active
},
财产:
{
_id: 1,
name: {
15: Lake View,
20: Vista al lago
},
cat_id : 1
status: Active
},
{
_id: 2,
name: {
15: The Apple,
20: La manzana
},
cat_id : 1
status: Active
},
{
_id: 3,
name: {
15: Blue Monday,
20: Lunes azul
},
cat_id : 2
status: Active
},
询问:
var langId = 15;
db.Property.aggregate([
{
$lookup:
{
from: 'Category',
localField: 'cat_id',
foreignField: '_id',
as: 'catdetails',
},
},
{
$project: {
_id: 1,
name: `$name.${langId}`,
cat_id: 1,
status: 1,
'catdetails._id': 1,
'catdetails.name': `$catdetails.name.${langId}`,
'catdetails.status': 1,
},
},
]);
结果:
[
{
"_id": 1,
"name": "Lake View",
"cat_id": 1,
"status": "Active",
"catdetails": {
"_id": "1",
"name":[ "Office" ],
}
},
{
"_id": 2,
"name": "The Apple",
"cat_id": 2,
"status": "Active",
"catdetails": {
"_id": "1",
"name":[ "Office" ],
}
},
{
"_id": 3,
"name": "Blue Monday",
"cat_id": 2,
"status": "Active",
"catdetails": {
"_id": 2,
"name":[ "Restaurant" ],
}
},
]
在 catdetails 中的结果对象name
出现在这样的数组符号中"name":[ "Restaurant" ]
我想要这个没有这样的数组符号"name":"Restaurant"
预期结果:
[
{
"_id": 1,
"name": "Lake View",
"cat_id": 1,
"status": "Active",
"catdetails": {
"_id": "1",
"name":"Office",
}
},
{
"_id": 2,
"name": "The Apple",
"cat_id": 2,
"status": "Active",
"catdetails": {
"_id": "1",
"name":"Office",
}
},
{
"_id": 3,
"name": "Blue Monday",
"cat_id": 2,
"status": "Active",
"catdetails": {
"_id": 2,
"name":"Restaurant",
}
},
]
如何将我的查询更改为这种类型的结果?
请试试这个:
var langId = 15;
db.Property.aggregate([
{
$lookup:
{
from: 'category',
localField: 'cat_id',
foreignField: '_id',
as: 'catdetails',
},
}, { $addFields: { name: `$name.${langId}`, catdetails: { $arrayElemAt: ["$catdetails", 0] } } },
{ $addFields: { 'catdetails.name': `$catdetails.name.${langId}` } }])
一些更改包括删除_id :1
,因为默认情况下它将保留$project
,不需要包括在内,此外,如果您要保留更多字段,则可以使用$addFields而不是 clumsy $project
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句