【问题标题】:Low level nested field is preferred than top level nested field in the Mongodb Projection在 Mongodb Projection 中,低级嵌套字段优于顶级嵌套字段
【发布时间】:2017-08-23 07:09:48
【问题描述】:

我在“testProjection”集合中插入了以下数据。

{
    "eventname" : "Ball Passed",
    "command" : {
        "name" : "Run",
        "strike" : 15,
        "score" : true,
        "duration" : 123
    }
},
{
    "eventname" : "Ball Passed",
    "command" : {
        "name" : "Run",
        "strike" : 12,
        "score" : false,
        "duration" : 597
    }
}

我的查询是:

db.testProjection.find({},{"command":0,"command.score":0})

实际结果:

{
    "_id" : ObjectId("599d27944be6e513549dd170"),
    "eventname" : "Ball Passed",
    "command" : {
        "name" : "Run",
        "strike" : 15.0,
        "duration" : 123.0
    }
},
{
    "_id" : ObjectId("599d27944be6e513549dd171"),
    "eventname" : "Ball Passed",
    "command" : {
        "name" : "Run",
        "strike" : 12.0,
        "duration" : 597.0
    }
}

预期结果:

{
    "_id" : ObjectId("599d27944be6e513549dd170"),
    "eventname" : "Ball Passed"
},
{
    "_id" : ObjectId("599d27944be6e513549dd171"),
    "eventname" : "Ball Passed"
}

在 mongodb 投影中,Mongodb 中的查询引擎更喜欢嵌套的低级投影而不是顶层投影。

这是 mongodb 中想要的行为吗?有什么方法可以使用 mongodb 查询来实现我的预期?

【问题讨论】:

  • 你也可以查看db.testProjection.find({},{"command.score":0, "command":0})的结果;)。
  • 是的,这是预期的行为。此外,如果您指定了 db.testProjection.find({},{ "command.score": 0, "command": 0 }) 的其他方式,则子属性将被删除,随后的排除甚至会删除其他属性,留下command: {}。所以意图通常是“堆叠”路径,如db.testProjection.find({},{ "command.score": 0, "command.duration": 0 }),如果你真的打算删除“一切”,那么你只会发出那个。但它实际上是“顺序优先”而不是“深度优先”。

标签: mongodb mongodb-query


【解决方案1】:

有什么方法可以使用 MongoDb 查询来实现我的预期?

您可以包含您的预期字段,而不是排除以下字段:

db.testProjection.find(
    {},
    {
        _id: 1,
        eventname: 1
    }
);

但我认为最好使用这样的聚合 - 作为性能问题 - :

db.testProjection.aggregate(
    [
        {
            $project: {
                _id : 1,
                eventname: 1
            }
        },
    ]
);

【讨论】:

    猜你喜欢
    • 2021-06-16
    • 2015-02-25
    • 2020-02-29
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    相关资源
    最近更新 更多