在insert_one()

时间:2019-06-25 20:44:11

标签: mongodb pymongo

我需要在特定领域将两个集合结合在一起,如下所示:

temp_recipes

{"_id":{"$oid":"5cf569311c9d440000dd30d6"},
"ingredients":["3 eggs","1/2 cup flour","1/2 cup milk","1 tbsp sugar","3/4 cup butter, divided","1/2 cup sugar","1 1/2 tsp cinammon","1-2 tbsp molasses","1 cup powdered sugar","2 tbsp half and half"],
"recipe_from":"Bob's Burgers",
"recipe_name":"Dutch Baby"

媒体

{"_id":{"$oid":"5cf56b7f1c9d440000dd30d8"},
"media_name":"Bob's Burgers",
"category":"TV","origin":"American",
"genres":["Comedy","Animation"]

我需要在recipe_from / media_name字段中加入它们,而我正努力将它们放入数据库。 temp_recipes集合是使用insert_one()从网站前端的表单中填写的,我一直在尝试使用$lookup阶段将表单加入后加入两个集合提交,因此集合将如下所示:

 {"_id":{"$oid":"5cf569311c9d440000dd30d6"},
"ingredients":["3 eggs","1/2 cup flour","1/2 cup milk","1 tbsp sugar","3/4 cup butter, divided","1/2 cup sugar","1 1/2 tsp cinammon","1-2 tbsp molasses","1 cup powdered sugar","2 tbsp half and half"],
"recipe_from":"Bob's Burgers",
"recipe_name":"Dutch Baby",
"category":"TV","origin":"American",
"genres":["Comedy","Animation"]

我的代码的当前设置如下,该表单正在触发insert_one(),但是media集合中的字段未插入temp_recipes集合中:

new_recipe = temp_recipes.insert_one(
    {
    "recipe_name": form["recipe_name"],
    "recipe_from": form["recipe_from"],
    "ingredients": flatForm["ingredients"],
    }
    )
temp_recipes.aggregate([
    {
        '$lookup':
            {
            'from': 'media',
            'localField': 'recipe_from',
            'foreignField': 'media_name',
            'as': 'recipe_media'}}
     ])

我不知道事情是否以错误的顺序进行,或者我犯了更大的错误,是否有人可以指出正确的方向,这将是很棒的-我对MongoDB和pymongo还是陌生的并大都糊涂了!

1 个答案:

答案 0 :(得分:0)

我已经弄清楚了这一点-我没有在代码中的任何地方调用temp_recipes.aggregate,所以我添加了$out来加入MongoDB中的两个集合。此处使用完整代码:

new_recipe = temp_recipes.insert_one(
    {
    "recipe_name": form["recipe_name"],
    "recipe_from": form["recipe_from"],
    "ingredients": flatForm["ingredients"],
    }
    )
temp_recipes.aggregate([
    {
    '$lookup':
        {
        'from': 'media',
        'localField': 'recipe_from',
        'foreignField': 'media_name',
        'as': 'recipe_media'
        }
    },
        {
        '$out': 'temp_recipes'
        }
     ])

这已将以下输出返回到temp_recipes集合中的数据库:

{"_id":{"$oid":"5d13c86b2f2c8421f8e381d6"},"recipe_name":"Grilled Frank",
"recipe_from":"It's Always Sunny In Philadelphia",
"ingredients":["Spam","Jelly pancake"]
"category":"TV",
"genres":["Comedy"]}

为清楚起见,对代码进行了稍微的编辑,但这就是我所知道的!