Arrays MongoDB-使用$elemMatch从阵列中选择多个子组件

Arrays MongoDB-使用$elemMatch从阵列中选择多个子组件,arrays,mongodb,mongodb-query,Arrays,Mongodb,Mongodb Query,我的收藏如下:- { _id: 5, "org_name": "abc", "items": [ { "item_id": "10", "data": [ // Values goes here ] }, { "item_id": "11", "data": [ // Values goes here ] } ] }, // Another s

我的收藏如下:-

{
  _id: 5,
  "org_name": "abc",
  "items": [
    {
      "item_id": "10",
      "data": [
        // Values goes here
      ]
    },
    {
      "item_id": "11",
      "data": [
        // Values goes here
      ]
    }
  ]
},

// Another sub document
{
  _id: 6,
  "org_name": "sony",
  "items": [
    {
      "item_id": "10",
      "data": [
        // Values goes here
      ]
    },
    {
      "item_id": "11",
      "data": [
        // Values goes here
      ]
    }
  ]
}
每个子文档对应于各个组织,每个组织中都有一个
项目的
数组

我需要的是通过提供
item\u id
items
数组中获取所选的单个元素

我已经试过了:-

db.organizations.find({"_id": 5}, {items: {$elemMatch: {"item_id": {$in: ["10", "11"]}}}})
但它返回的是带有*item\u id*“10”
的项目列表或带有*item\u id*“11”的项目列表


我需要的是组织“abc”的第10项和第11项的get值。请帮助。

更新2

db.organizations.aggregate([
    // you can remove this to return all your data
    {$match:{_id:5}},
    // unwind array of items
    {$unwind:"$items"},
    // filter out all items not in 10, 11
    {$match:{"items.item_id":{"$in":["10", "11"]}}},
    // aggregate again into array
    {$group:{_id:"$_id", "items":{$push:"$items"}}}
])
db.organizations.find({
    "_id": 5,
    items: {$elemMatch: {"item_id": {$in: ["10", "11"]}}}
})
更新

db.organizations.aggregate([
    // you can remove this to return all your data
    {$match:{_id:5}},
    // unwind array of items
    {$unwind:"$items"},
    // filter out all items not in 10, 11
    {$match:{"items.item_id":{"$in":["10", "11"]}}},
    // aggregate again into array
    {$group:{_id:"$_id", "items":{$push:"$items"}}}
])
db.organizations.find({
    "_id": 5,
    items: {$elemMatch: {"item_id": {$in: ["10", "11"]}}}
})
old看起来您需要,尤其是操作员:

db.organizations.aggregate([
    {$match:{_id:5}}, // you can remove this to return all your data
    {$unwind:"$items"}
])

谢谢你的回答。但是我需要的不是选择所有的
项目
。如果我不清楚,很抱歉,但我需要的是指定我需要从中获取数据的项目的
item\u id
s。@Sparky确定,请参阅更新,我们将查看我现在是否理解您:)。您必须在
find
的第一个参数中指定
items
。我想您现在明白我需要什么了,但是更新后的查询也为我提供了给定组织中的所有项(_id:5):(@Sparky ok,第三次尝试,如果您想从数组中筛选出一些元素,我想您仍然需要聚合框架:),见UpdatedTanks@Roman,它的工作:):)非常感谢。还有一点小疑问。当前,输出仅具有
项目id
。如果我还需要获取一些关于返回项目的其他属性,比如
item\u id
item\u name
,该怎么办?你能更新你的答案吗??)