通过一个字段的存在在mongodb中子数组

时间:2019-03-13 21:52:18

标签: mongodb pymongo

我有一个这样的收藏集pub_fulltext_1

{
   _id: 0,
   author:Jose Fernandez,
   year: 2019,
   reference: [
     { item_id: 43, author: Alberto Perez, year: 1910, context: some text },

     { item_id: 44, author: Lucas Leys, year: 1990, context: some text },

     { item_id: 45, author: Johan Ortiz, year: 2005}
   ]
}
{
   _id: 1,
   author: Ramiro Ramirez,
   year: 2015,
   reference: [
     { item_id: 68, author: Mats Valk, year: 1993, context: some text },

     { item_id: 74, author: Robert Lucas, year: 1976, context: some text },

     { item_id: 80, author: Mark Ljumberg, year: 2005, context: some text}
   ]
}
{
   _id: 2,
   author: Feliks Zemdges,
   year: 2018,
   reference: [
     { item_id: 1, author: Gan Zandhi, year: 2015},

     { item_id: 2, author: Dayan Wojung, year: 1976, context: some text },

     { item_id: 80, author: Mats Valk, year: 2014}
   ]
}

我需要制作一个新集合pub_context,该集合只有带有上下文的引用字段,像这样:

{
   _id: 0,
   author:Jose Fernandez,
   year: 2019,
   references: [
     { item_id: 43, author: Alberto Perez, year: 1910, context: some text },

     { item_id: 44, author: Lucas Leys, year: 1990, context: some text }
   ]
}
{
   _id: 1,
   author: Ramiro Ramirez,
   year: 2015,
   references: [
     { item_id: 68, author: Mats Valk, year: 1993, context: some text },

     { item_id: 74, author: Robert Lucas, year: 1976, context: some text },

     { item_id: 80, author: Mark Ljumberg, year: 2005, context: some text}
   ]
}
{
   _id: 2,
   author: Feliks Zemdges,
   year: 2018,
   references: [
     { item_id: 2, author: Dayan Wojung, year: 1976, context: some text },
   ]
}

我正在尝试没有结果的

1。

pipeline=[db.pub_fulltext_1.aggregate([
{"$match":{"references":{"$elemMatch":{"context":{"$exists": "true"}}}}},
{"$out": "pub_context"}
])]

2。

pipeline=[db.pub_fulltext_1.aggregate([
{"$project":{"references":{"$filter":{"input": "$context", "as":"context","cond":{"$exists": "true"}}}}},
{"$out": "pub_context"}
])]

3。

pipeline=[db.pub_fulltext_1.aggregate([
{"$match":{"references.context":{"$exists": "true"}}}}},
{"$out": "pub_context"}
])]

4。

pipeline=[db.pub_fulltext_1.aggregate([
{"$match":{"references.context":{"$exists": "true","$ne":"null"}}},
{"$out": "pub_context_3_p"}
])]

5。

pipeline=[db.pub_fulltext_1.aggregate([
{
  "$project": {
        "author":1,            
        "year":1,
        "references": {
        "$filter": {
        "input": "$references",
        "as": "item",
        "cond": {"$ifNull":["$$item.context","null"]}
        }
        }
        }
        },
        {"$out": "pub_context_17_p"}
        ])]

任何想法我该怎么做?

1 个答案:

答案 0 :(得分:0)

尝试这个。

db.collection.aggregate([
{
  $project: {
        author:1,
        year:1,
     reference: {
        $filter: {
           input: "$reference",
           as: "item",
           cond: {$ifNull:["$$item.context",null]}
        }
     }
  }
}
])