本文介绍了访问 MongoDB 中的嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个具有以下架构的 MongoDB 集合.

We have a MongoDB collection with the following schema.

    Sales {
       salesID:"SO-0002"
       dispatches: [
          {
           "dispatchNo" : "SO-0002/dispatch/1",
        "date" : "2014-05-31T18:30:00.000Z",
        "location" : "l1",
        "items": [{
                     //itemDetails
                 }]
          },
          {
           "dispatchNo" : "SO-0002/dispatch/2",
        "date" : "2014-05-31T18:30:00.000Z",
        "location" : "l2",
        "items": [{
                     //itemDetails
                 }]
          }
       ]
    }

执行以下查询时:

db.sales.find({salesOrderNo:"SO-0002",'dispatches.dispatchNo':"SO-0002/dispatch/1"}).pretty()

我们希望只获得调度 1 的详细信息,但我们仍然获得了所有调度的详细信息.

We expect to get only the details of the dispatch 1, but we are still getting the details of all the dispatches.

我们是否遗漏了什么?

谢谢.

推荐答案

是的.这是预期的行为.dispatches 是父文档中的一个数组.当一个文档匹配时,整个文档被返回.解决此问题的唯一方法是将您的架构更改为多个集合,或者使用聚合框架或映射/缩减.

Yes. This is the expected behavior. dispatches is an array within the parent document. When a document is matched, the document is returned in its entirety. The only way around this is to change your schema into multiple collections, or to use the aggregation framework or map / reduce.

这篇关于访问 MongoDB 中的嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 20:07