arrays - Node.JS + MongoDB 聚合 从 MongoDB 中的数据库中查找数组中的数组

标签 arrays node.js mongodb

我在 MongoDB 中有一个模型,其中包含一个数组(类别),其中有一个数组(图片)。 衬衫模特看起来像这样:

{ _id: 100, category: [ { name: 'CatName', _id: 101, picture: [Object] } ] }

我的图片数组是这样的:

 [ { path: 'p1', _id: 102 },
   { path: 'p2', _id: 103 } ] }

我传递了 3 个变量

  1. 主数组 ID 为 100 (var1)
  2. 类别名称是 CatName (var2)
  3. 图片id为102 (var3)

我想获取一个如下所示的数组:

{ _id: 100, category: [ { name: 'CatName', _id: 101,
                          picture: [ { path: 'p1', _id: 102 }]  
                        } ]
}

我试过的是这样的:

Shirt.find(   {_id: var1} ,  
{category: { $and:[ { name: var2 } , { picture: {$elemMatch: {_id: var3}}}  ] }}  )
.exec(function(err, product) {
    console.log('Result  ' + product );
    res.jsonp(product);
});

但我收到的结果是未定义的第一个代码

我尝试的第二个代码:

Shirt.find( {_id: var1} ,
            {category: {$elemMatch: { name: var2,picture: {$elemMatch: {_id: var3} }}} }  )

并且第二个代码的结果过滤了 var1var2 的数组 但它包含整个图片数组,这意味着它不会过滤 var3

  1. 找到我想要的内容的正确代码是什么?
  2. 这是购物网站数据库的正确方法吗?或者您有更好的建议吗?
  3. 我是否正确应用父子数据库?

谢谢!

最佳答案

下面的 mongo 查询会给你预期的结果:

db.collection.find({
    "category": {
    $elemMatch: {
        "name": "CatName",
        "picture": {
            $elemMatch: {
                "_id": 102
            }
        }
    }
    }
})

需要转成node.js格式

以下格式可能对您有所帮助。 未测试

collection.find({
    _id: "" // add your match Id here} ,  
        {
            category: {
                "$elemMatch": {
                    "name": "CatName",
                    "picture": {
                        $elemMatch: {
                            "_id": 102
                        }
                    }
                }
            }
        }
    })
    .exec(function(err, product) {
    console.log('Result  ' + product);
    res.jsonp(product);
    });

编辑问题后

你应该使用 mongo aggregation获得所需的值。查询将如下所示 -

db.collection.aggregate({
    $unwind: '$category'
}, {
    $unwind: '$category.picture'
}, {
    $match: {
    _id: 100, // add here your var1 variable instead of 100
    'category.name': 'CatName', // add here your var2 variable instead of 'CatName'
    'category._id': 102, //add your match id here if any otherwise remove this condition
    'category.picture._id': 102 //add your var3 instead of 102
    }
}, {
    $group: {
    _id: '$category.name',
    'name': {
        $first: '$category.name'
    },
    'picture': {
        '$push': '$category.picture'
    }
    }
})

关于arrays - Node.JS + MongoDB 聚合 从 MongoDB 中的数据库中查找数组中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30567073/

相关文章:

Node.js/了解 ReadStream.pipe 是否正在传输数据

arrays - Matlab:重复行和列并将其连接到新数组中

javascript - 语法错误: Unexpected token

c++ - 请求想法 - 如何对具有多行和 3 列的二维数组进行排序,维护数据行

node.js - nodejs elastic Client错误:将应用程序托管到服务器后,映射不能具有多种类型[默认,_doc]

java - 使用 Java 从 MongoDB 获取随机文档/记录

javascript - 如何安全地执行操作,然后从 .txt 文件中异步插入 250,000 多个单词,而不会导致堆栈溢出?

node.js - 使用node.js查询mongoDB的特定字段

python - 为 OpenCV imshow 连接 Numpy 数组

c# - 检查 2 个 int 数组是否仅包含同一索引处的唯一数字