gpt4 book ai didi

arrays - MongoDB:如何获取查找集合的对象值

转载 作者:太空宇宙 更新时间:2023-11-03 23:51:14 25 4
gpt4 key购买 nike

我是 MongoDB 新手。我想找到对象值来查找集合。

以下是集合:

语言:

{
_id: 15,
language:English,
status: Active
},
{
_id: 20,
language:Spanish,
status: Active
},

类别:

这里15, 20name对象中的语言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而不是笨拙的$project

引用: $arrayElemAt , $addFields

关于arrays - MongoDB:如何获取查找集合的对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59425061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com