mongodb投影 - 从数组中获取第一个元素

发布于 2025-02-10 19:52:10 字数 195 浏览 1 评论 0原文

我的字段“ field1.field2”是一个数组,我只想获取此数组的第一个元素,即“ field1.field2.0”,我想以其他任何给定的字段为例:“ field1.field2.0 .field3“。不幸的是,当我在Pymongo中使用此投影时,它不起作用(这个“ 0”会出现问题)。投影不会丢弃错误,但是“ 0”字段在投影之前包含值后的投影后不包含任何值。原因是什么?

My field "Field1.Field2" is an array and I want to take only first element of this array, i.e. "Field1.Field2.0" and from this I want to take any other given field for example: "Field1.Field2.0.Field3". Unfortunately when I use this projection in PyMongo then it doesn't work (this "0" make problems). The projection doesn't throw an error but the field "0" doesnt contain any values after projection while it contain the values before projection. What may be the reason?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

节枝 2025-02-17 19:52:10

选项1:聚合/$ arrayat或$ first

db.collection.aggregate([
{
  $addFields: {
     x: {
      "$arrayElemAt": [
        "$x",
        0
       ]
     }
   }
 }
])

playground 1

选项2:聚合/$ slice

db.collection.aggregate([
{
 $addFields: {
  x: {
    "$slice": [
      "$x",
      1
    ]
   }
  }
 }
])

Playground 2

/$ slice

db.collection.find({},
{
  x: {
    $slice: 1
  }
})

Playground 3

Option 1:aggregation/$arrayAt or $first

db.collection.aggregate([
{
  $addFields: {
     x: {
      "$arrayElemAt": [
        "$x",
        0
       ]
     }
   }
 }
])

Playground 1

Option 2:aggregation/$slice

db.collection.aggregate([
{
 $addFields: {
  x: {
    "$slice": [
      "$x",
      1
    ]
   }
  }
 }
])

Playground 2

Option 3:find/project/$slice

db.collection.find({},
{
  x: {
    $slice: 1
  }
})

Playground 3

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文