查询mongodb中的数组对象数组

时间:2016-07-10 07:36:33

标签: arrays mongodb mongoose

以下是我在mongodb的产品系列..

{
    "_id" : ObjectId("56d42389db70393cd9f47c22"),
    "sku" : "KNITCHURI-BLACK",
    "options" : [
        {
            "sku" : "KNITCHURI-BLACK-M",
            "stores" : [
                {
                    "code" : "6",
                    "quantity" : 0
                },
                {
                    "code" : "10",
                    "quantity" : 26
                }
            ],
            "ean_code" : "2709502",
            "size" : "M"
        },
        {
            "sku" : "KNITCHURI-BLACK-S"
            "stores" : [
                {
                    "code" : "6",
                    "quantity" : 0
                },
                {
                    "code" : "10",
                    "quantity" : 30
                }
            ],
            "size" : "S"
        }
    ]
}

想要查询{ 'options.stores.code' : '6' }{ 'options.stores.quantity' : { $gt : 0 } }的位置,我如何查询此集合然后我得到了回复?请帮助解决这个问题。

3 个答案:

答案 0 :(得分:1)

据我了解这个问题,您希望在商店中找到代码为6的库存产品。以下查询可以做到:

db.collection.find({"options.stores" : {$elemMatch: {"code" : "6", "quantity" : {$gt : 0}}}});

答案 1 :(得分:1)

我认为你需要展开选项

db.product.aggregate( [ 

{ $unwind: "$options" }
{ $match: { 'options.stores.code' : '6','options.stores.quantity' : { $gt : 0 }}


] )

答案 2 :(得分:1)

以下是在Mongoose中获取文档的两种方法。

如果需要,可以在各种答案中更改Mongo查询。我刚用你的方法进行Mongo查询。

方法1 - 使用光标 - 推荐方法
方法2 - 使用查询

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;

var Store = new Schema({
    code : String,
    quantity : Number
});

var Option = new Schema({
    sku : String,
    stores : [ Store ],
    ean_code : String,
    size : String

});

var productSchema = new Schema({
    _id : ObjectId,
    sku : String,
    options : [ Option ]
});

var Product = mongoose.model('product', productSchema, 'product');

console.log("Cursor Approach #1");
var cursor = Product.find({
    'options.stores' : {
        $elemMatch : {
            code : '6',
            quantity : {
                $gt : 0
            }
        }
    }
}).cursor();

console.log("Curosr Results***************************************");
cursor.on('data', function(doc) {
    console.log("Getting doc using cursor ==========>" + JSON.stringify(doc));
});
cursor.on('close', function() {
    console.log("close the cursor");
});

console.log("Query Approach #2");

var query = Product.find({
    'options.stores' : {
        $elemMatch : {
            code : '6',
            quantity : {
                $gt : 0
            }
        }
    }
});

console.log("Query Results***************************************");
query.exec(function(err, doc) {
    if (err) {
        console.log(err);
    }

    console.log("Getting doc using query ==========>" + JSON.stringify(doc));
});