AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

问题[mongodb](coding)

Martin Hope
Orion
Asked: 2025-04-10 01:03:36 +0800 CST

如何查找包含子元素数组且子元素有 ID 的文档

  • 6

我希望有人能帮忙。

我接手了一个使用 Atlas Mongo DB 的项目。项目要求我从一个集合中获取数据。假设集合中的文档结构如下:

{ _id: 'Parent1', kids: [ { _id: 'Test1', grandkids: [ { name: 'Blah' } ] } ] },
{ _id: 'Parent2', kids: [ { _id: 'Test1', grandkids: [ { name: 'Bloh' } ] } ] },
{ _id: 'Parent3', kids: [ { _id: 'Test2', grandkids: [ { name: 'Bloh' } ] } ] }

当孩子的 _id 为“Test 1”时,我需要获取名字为“Bloh”的孙子,这应该返回来自第二个文档的数据。

使用 Cloud MongoDb Web UI,我尝试进行如下查询,只是想看看是否可以找回第二个文档:

{
    '$and': [
        { 'kids._id': ObjectId('Test 1') },
        { 'kids.grandkids.name': 'Bloh' }
    ]
}

但我没有得到任何结果。我怀疑可能是因为 kids 中的 _id 不唯一。

假设我可以拿回第二份文件,我该如何拿回匹配的孙子呢?

提前致谢!

编辑:

使用 MongoDb 游乐场,这可能是一个问题:

无效查询:

第 3 行:无效的 ObjectId:哈希值必须为 24 个字符长

不幸的是,kid._id 不仅重复,而且长度也不总是 24 个字符。

mongodb
  • 1 个回答
  • 37 Views
Martin Hope
dinx
Asked: 2025-04-04 02:53:59 +0800 CST

最佳 Mongo 聚合将一个集合中的 _ids 数组映射到另一个集合中的值

  • 6

我有两个相关的 mongo 集合。这些示例文档说明了它们的关系:

// "things" collection example document:
{
  _id: 1,
  categories: [123, 234],
  // other fields
}

// "categories" collection example documents:
{
  _id: 123,
  value: "Category name"
},
{
  _id: 234,
  value: "Other category name"
}

我一直在尝试找到一种方法,将文档类别数组中的 ID 号映射things到集合中相应文档的值categories。根据上述示例,您最终将得到以下文档:

{
  _id: 1,
  categories: [
    "Category name",
    "Other category name",
  ],
  // other fields
}

我的问题是我当前的管道过于复杂,并且肯定会执行不必​​要的操作,从而造成潜在的性能问题。我当前的管道是:

  • (起点)
{
  _id: 1,
  categories: [123, 234],
  // other fields
}
  • $unwind类别
{
  _id: 1,
  categories: 123,
  // other fields
},
{
  _id: 1,
  categories: 234,
  // other fields
}
  • $lookup在类别集合上将新的本地“类别”字段与外部“_id”匹配
{
  _id: 1,
  categories: [{ _id: 123, value: "Category name" }],
  // other fields
},
{
  _id: 1,
  categories: [{ _id: 234, value: "Other category name" }],
  // other fields
}
  • $addFields用{ $arrayElemAt: [ "$categories", 0 ] }我最初想要的文档替换数组
{
  _id: 1,
  categories: { _id: 123, value: "Category name" },
  // other fields
},
{
  _id: 1,
  categories: { _id: 234, value: "Other category name" },
  // other fields
}
  • $addFields使用{ categories: "$categories.value" }值字段替换整个文档
{
  _id: 1,
  categories: "Category name",
  // other fields
},
{
  _id: 1,
  categories: "Other category name",
  // other fields
}
  • $group“撤消”原始展开。我使用_id: "$_id"和{ $addToSet: "$categories" }(以及格式中的许多其他属性<field-name>: { $first: "$<field-name>" }来重新添加所有“其他字段”)
{
  _id: 1,
  categories: [
    "Category name",
    "Other category name",
  ],
  // other fields
}

我担心我缺少效率更高的聚合函数,因此当我将来在大量文档上使用它时,会产生缓慢且昂贵的读取操作,但我找不到更干净的解决方案。任何正确的方向的推动都将不胜感激。

mongodb
  • 1 个回答
  • 26 Views
Martin Hope
Nikolay Kovalenko
Asked: 2025-03-24 19:40:27 +0800 CST

MongoDB:重命名带有点的字段

  • 5

我有一个 MongoDB 集合,其中包含几个带点的字段,例如:

{
    "symbol.name": "Some name"
    "symbol.state": "Some state"
    // etc.
}

现在,我需要将“symbol.name”重命名为“symbol”,并删除其余以“symbol.”开头的字段。到目前为止,这些方法对我都不起作用。通常,字段保持不变,没有任何变化。我们使用的是 Mongo 4.4 和 pymongo。

这个问题有解决办法吗?

mongodb
  • 1 个回答
  • 60 Views
Martin Hope
Cutty Shark
Asked: 2025-03-22 17:29:43 +0800 CST

Rust mongodb 重复键错误处理

  • 5

在我的 Rust 应用程序中,我需要对重复键(代码 11000)错误进行特殊处理。我想出了这个解决方案,但它看起来很复杂。有没有更好的方法?

let res = collection.insert_one(entry).await;
match res {
        Ok(_) => Ok(()),
        Err(e) => {
            // println!("{:?}", e);
            match *e.kind {
                ErrorKind::Write(failure) => {
                    match failure {
                        WriteFailure::WriteError(we) => {
                            if we.code == 11000 { Ok(()) }
                            else { Err("other write failure".into()) }
                        },
                        _ => Err("other write error".into()),
                    }
                },
                _ => Err("other error".into()),
            }
       },
    }
mongodb
  • 1 个回答
  • 56 Views
Martin Hope
Pavithra
Asked: 2025-02-14 15:22:10 +0800 CST

Guid 序列化子类型

  • 3

mongodb guid 表示模式导致了一些问题,在图形 API 中必须将其明确指定为“标准”。

  • mongodb 6 中默认使用的是什么以及与之关联的 C# 驱动程序是什么?
  • mongodb 8 中的默认设置以及与其关联的 C# 驱动程序是什么?
  • 哪种表现模式最好以及应该使用什么?
  • 更换为新的是否会导致任何向后兼容性问题?
mongodb
  • 1 个回答
  • 25 Views
Martin Hope
Tony
Asked: 2025-02-07 18:29:12 +0800 CST

打字稿中的依赖下拉框不起作用

  • 5

我是 Typescript React 的新手,我试图创建两个从属选择框来从 API 中获取数据,但遇到了一点困难。当我在类别中选择颜色时,我只希望在产品下拉菜单中选择颜色,但我也得到了所有其他产品,而且它在一个选项中水平显示所有颜色。这是我到目前为止尝试过的方法。

在此处输入图片描述

我的 MongoDB 结构

  "_id": {
    "$oid": "679a70442a02723a1ad65e5d"
  },
  "categoryName": "Colours",
  "productName": [
    {
      "productName": "Red"
    },
    {
      "productName": "Blue"
    },
    {
      "productName": "Yellow"
    },
    {
      "productName": "Green"
    }
  ],
  "productQuantity": 90,
  "ordUpdated": {
    "$date": "2025-01-29T18:15:32.969Z"
  },
  "isInStock": false,
  "_class": "com.softoffice.portal.model.OrderDTO"

打字稿

export const DependentDropdown = () => {
  const [selectedCateogary, setSelectedCategory] = useState('');
  const [selectedProd, setSelectedProd] = useState([]);

  const { data } = useQuery({
    queryKey: ["ordlist"],
    queryFn: () => fetch("http://localhost:8080/portal")
      .then((res) => res.json())
  })

  const products = data?.map((row: any) => ({
    productName: row.productName?.map((p: { productName: string; }) => p.productName)
  }))

  const handleChange = (id:string) => {
    const pd = products.filter((c: any) => c.categoryName === id);
    setSelectedProd(pd);
  }

  return (
    <div>
      <InputLabel id="demo-simple-select-label">Category</InputLabel>
      <select className='select' onChange={(e) => handleChange(e.target.value)} >
    <option>Select Category</option>
    {data?.map((row: { categoryName: any }) => (
      <option>{row.categoryName}</option>
    ))}
      </select>

      <InputLabel id="demo-simple-select-label">Product</InputLabel>
      <select className='select' >
    <option>Select Product</option>
    {data?.map((row: { productName: any }) => (
      <option>{row.productName?.map((p: { productName: string; }) => p.productName)}</option>
    ))}
      </select>
    </div>
  );
}
mongodb
  • 1 个回答
  • 24 Views
Martin Hope
user824624
Asked: 2025-02-03 23:16:28 +0800 CST

使用 $addToSet 更新 mongodb 的数组并使用 { '$size': '$array' } 设置数组的长度不起作用

  • 6

我正在研究具有如下模型的 mongodb

const appJobSchema = new mongoose.Schema({
    data:[
        { type:Schema.Types.Mixed}
    ],
    stat:{
      dataCount: { type:Number , default: 0 },
    }
})

我需要做的是将一些记录更新到mongodb数组字段-data,同时将最新的数组长度更新到stat.dataCount字段。

export async function updateDataById(id:string, records:any[]){
  return await model.updateOne({'_id':id}, {  
    '$addToSet': { 'data': { '$each': records } } ,  
    '$set':{ 
      'stat.dataCount': { $size: "$data" }  } 
  } );
}

但我收到错误说

uncaughtException: Cast to Number failed for value "{ '$size': '$data' }" (type Object) at path "stat.dataCount"

知道我该怎么做吗?

更新

管道上的首次尝试

return await model.updateOne({'_id':id}, 
    [
    {
      "$set": {
        "data": {
          $concatArrays: [ "$data",  records  ]
        }
      }
    },
    { 
      '$set':{ 
        'stat.dataCount': { $size: "$data" }  }  
    }
  ]);

它可以工作,但问题是仅仅向数据数组添加值就会导致重复的值,这就是为什么我必须使用 $addToSet 来删除重复的值。

管道第二次尝试

Model.updateOne({'_id':id},
    [
      {  '$addToSet': { 'data': { '$each': records } },  '$inc':{ 'runCount': 1  } , 
      { 
        '$set':{ 
          'stat.dataCount': { $size: "$data" }  }  
      }
  ]);

它抛出了 uncaughtException:无效的更新管道运算符:“$addToSet”。$inc 也是一样。

最后通过 $setUnion 和管道让它工作,

await Model.updateOne({'_id':id},
    [   
      {
      "$set": {
        "data": {
          $setUnion: [ "$data",  records  ]
        }
      }
    },
    { 
      '$set':{ 
        'stat.dataCount': { $size: "$data" }  }  
    },
  ]);

但是如果我需要使用 $inc,这似乎仍然是一个问题。

mongodb
  • 1 个回答
  • 62 Views
Martin Hope
Tony
Asked: 2025-01-21 16:50:31 +0800 CST

如何使用 Spring boot 在 mongoDB 中使用通配符?

  • 6

我正在尝试运行一个简单的搜索查询,但它返回一个空数组,数据库中大约有三条记录。我还有其他查询,它们都运行正常。有人能给我指出正确的方向吗?

模型

@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "order")
public class OrderDTO {
    
    @Id
    private String ordId;
    private List<Category> categoryName;
}

存储库

@Repository
public interface OrderRepository extends MongoRepository<OrderDTO, String> {

    @Query("{'categoryName': {'$regex': ?0 }})")
    public List<OrderDTO> findByCategoryName(String categoryName);
}

服务

public List<OrderDTO> searchOrderByCategoryName(String categoryName){
    return or.findByCategoryName(categoryName);
    }
    

控制器

@RestController
@RequestMapping("/portal")
@CrossOrigin(origins = "http://localhost:3000")
public class OrderController {

    @Autowired OrderService os;
    
    @GetMapping("/search/{categoryName}")
    public List<OrderDTO> searchOrderByCategoryName(@PathVariable(value = "categoryName") String categoryName) {
    return os.searchOrderByCategoryName(categoryName);
}

数据库

    {
  "_id": {
    "$oid": "678ed41ceac5b05ec1a2dea8"
  },
  "categoryName": [
    {
      "categoryName": "N"
    }
  ],
  "productName": [
    {
      "productName": "9999999"
    },
    {
      "productName": "888888"
    },
    {
      "productName": "77777777"
    },
    {
      "productName": "55555555"
    }
  ],
  "productQuantity": 90,
  "ordUpdated": {
    "$date": "2025-01-20T22:54:20.729Z"
  },
  "isInStock": false,
  "_class": "com.softoffice.portal.model.OrderDTO"
}
mongodb
  • 1 个回答
  • 21 Views
Martin Hope
basse
Asked: 2025-01-06 16:59:57 +0800 CST

解构单个文档的数组字段以在 Mongo 中输出文档

  • 6

我在 MongoDB 中使用以下聚合管道来遍历双向图:

{ $match: { from: "some_root" } },
{
  $graphLookup: {
    from: "connections",
    startWith: "$to",
    connectFromField: "to",
    connectToField: "from",
    as: "children",
    depthField: "depth",
    maxDepth: 100
  },
}

connection使用我的数据结构,这会导致零个或多个输出文档,这些文档在其字段中都具有相同的文档数组children。我想对这些connection文档进行进一步处理,但避免处理重复项。

我如何才能仅选择第一个文档的children数组并将它们提升为输出文档,以便在管道的下一步中进行处理?

添加以下阶段可以得到我想要的结果,但是该$graphLookup阶段的每个输出文档都会有重复的文档:

{ $unwind: { path: "$children" } },
{ $replaceRoot: { newRoot: "$children" } }

对我来说,这似乎是语义上正确的方法,并且它之前只缺少一个对“ $select”children第一个文档的字段进行处理的阶段。

我知道一个$group阶段可能能够过滤掉重复项,但这感觉像是对一个简单问题的复杂解决方案(即,如果您可以避免出现这些重复项,为什么要过滤掉重复项)。

澄清伪示例

该$graphLookup阶段的结果是:

{
  _id: 1,
  children: [
    { _id: 10 },
    { _id: 11 }
  ]
},
{
  _id: 2,
  children: [
    { _id: 10 },
    { _id: 11 }
  ]
}

我希望从中提取一组children并将它们提升为文档,以便用于管道的后续步骤,即作为输入文档:

{ _id: 10 },
{ _id: 11 }
mongodb
  • 1 个回答
  • 31 Views
Martin Hope
Tom3652
Asked: 2024-12-19 21:44:22 +0800 CST

为什么 MongoDB 没有为特定查询选择我的索引?

  • 5

我有以下post文件:

post = {"_id": "postID1", "userID": "userID1", "likeNum": 10, "url": "anyUrl"}

我有一个疑问:

posts_collection.find({"userID": {"$nin": ["uid1", "uid2"]}, "_id": {"$nin": ["postID1", "postID2"]}}).sort("likeNum", DESCENDING).limit(30).explain()

我的聚合管道:

  pipeline = [
            {"$match":{"userID": {"$nin": ["uid1", "uid2"]}, "_id": {"$nin": ["postID1", "postID2"]}}},
            {"$sort": {"likeNum": -1}},
            {"$group": {"_id": "$userID", "posts": {"$firstN": {"input": "$$ROOT", "n": 2}}}},
            {"$unwind": "$posts"},
            {"$replaceWith": "$posts"},
            {"$sort": {"likeNum": -1}},
            {"$limit": 30}
        ]
posts_collection.aggregate(pipeline)

我已经建立了一个索引likeNum: -1和另一个复合索引userID: 1, _id: 1, likeNum: -1

该explain()方法始终显示它将进行likeNum: -1并执行集合扫描。

并且我的聚合管道explained输出也在我的 MongoDB Atlas 仪表板中的查询分析器中显示相同的信息。

是因为内存排序的性能$nin不如集合扫描吗?还是其他原因?

注意:有时查询可能只有过滤器,userID而没有过滤器_id,也可能有相反的过滤器(_id没有过滤器userID),或者没有这些过滤器(在这种情况下,我理解为likeNum: -1)。

如果这有助于理解这种行为,那么该集合中我有 10k 个文档。

mongodb
  • 1 个回答
  • 35 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve