Mongodb经过条件查询后获取的是整个文档?
仅有的幸福
仅有的幸福 2017-05-02 09:24:53
0
2
632

例如有组数据:

name: 'food',
data: {
    fruit: [
        {
            name: 'apple',
            stock: 10
        },
        {
            name: 'pear',
            stock: 66
        }
        ...
    ]
            
}

db.col.find({'data.fruit.stock': 66}, {data.fruit.stock: 1})

查询到的是整个data.fruite;

Q1: 有什么方法只获取过滤器查询的那条数据吗?如果这个文档对象量比较大咋办?
Q2: 这是Mongodb的一种特性?命中过滤器的条件后,返回的是整个文档对象?
Q3: 有这方面的API文档可参阅么?

仅有的幸福
仅有的幸福

reply all(2)
刘奇

The question asked by the questioner is actually related to the trade-off between Data Model and business query.

1. MongoDB returns basically the unit of document each time. If the document contains an array (Array), all arrays need to be returned;

2. As the subject wishes, if you want to follow the query conditions and just return the data in the array that meets the conditions, you can consider

1)重新设计data model,不使用数组嵌套;

2)使用$unwind,将数组按照Flat展开,可以参考下面这个帖子:     

/q/10...

For reference.

Love MongoDB! Have Fun!

------------------------Gorgeous separator--------------------- ----------

MongoDB Chinese community has many offline activities, please click below:

2017 Huashan Sword Discussion|MongoDB Chinese Community

Hangzhou Station is coming in March! ! ! Interested friends please sign up quickly! ! !

漂亮男人
> db.example.find().pretty()
{
    "_id" : ObjectId("58b50cd6a7329db9121efa00"),
    "name" : "food",
    "data" : {
        "fruit" : [
            {
                "name" : "apple",
                "stock" : 10
            },
            {
                "name" : "pear",
                "stock" : 66
            }
        ]
    }
}
> db.example.find({'data.fruit.stock':66}, {'data.fruit.stock': 1}).pretty()
{
    "_id" : ObjectId("58b50cd6a7329db9121efa00"),
    "data" : {
        "fruit" : [
            {
                "stock" : 10
            },
            {
                "stock" : 66
            }
        ]
    }
}

It will indeed return the stock of data.fruit data; but it can also return the stock of conditions, but you need to know the index number of stock in the fruit array.

That’s

 {'data.fruit.1.sock': 1}

Reference (mongodb version 3.4):
https://docs.mongodb.com/manu...
https://docs.mongodb.com/manu...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!