簡體   English   中英

find_one()返回一個給出字段組合的文檔

[英]find_one() return one document give a combination of fields

我正在嘗試從mongodb返回文檔(使用pymongo)。 我希望查詢返回給定ID和標簽的文檔。

ids = ['123', '456', '234', '534']

rows = []
for i in ids:
    for b in ["Tag1", "Tag2", "Tag3"]:
        temp = pb_db.db.collection.find_one({"ID": i, "Tag": b}, {'ID': 1, 'Tag': 1, 'Name': 1, '_created_at': 1})
        if temp is not None:
            rows.append(temp)

ID為'123'的文檔可能具有一個帶有'Tag1'的記錄,而另一個文檔具有'Tag3'。 “ ID”和“ Tag”的任何組合都是可能的。

目標是返回每個ID,標記組合的一個實例(因此使用find_one())

目前,我上面的代碼效率很低,因為它為每個id查詢數據庫3次(我的id列表比此示例大得多)。 是否可以使用find_one()查詢為每個標簽返回給定ID的文檔一次? 謝謝,

示例mongo結構:

{
    "_id" : "random_mongo_id",
    "Tag" : "Tag1",
    "_created_at" : ISODate("2016-06-25T00:00:00.000Z"),
    "ID" : [ 
        "123"
    ],
},
{
    "_id" : "random_mongo_id",
    "Tag" : "Tag2",
    "_created_at" : ISODate("2016-07-25T00:00:00.000Z"),
    "ID" : [ 
        "123"
    ],
},
{
    "_id" : "random_mongo_id",
    "Tag" : "Tag1",
    "_created_at" : ISODate("2016-07-25T00:00:00.000Z"),
    "ID" : [ 
        "534"
    ],
}

因此,在此示例中,我希望看到:

ID: 123, Tag: Tag1
ID: 123, Tag: Tag2
ID: 534, Tag: Tag1

您需要使用$in$elemMatch查詢運算符。

ids = ['123', '456', '234', '534']
tags = ["Tag1", "Tag2", "Tag3"]

db.collection.find_one({
    "Tag": { "$in": tags}, 
    "ID": { "$elemMatch": { "$in": ids}}
})

您可以使用$ in運算符將數據庫中“ ID”數組中的項目與“ ids”數組變量中的項目(以及類似地用於標記)進行比較,從而一次性完成。

使用$ in運算符匹配數組中的值

收集清單包含包含字段標簽的文檔,如下所示:

{ _id: 1, item: "abc", qty: 10, tags: [ "school", "clothing" ], sale: false }

然后,下面的update()操作會將sale字段的值設置為true,其中tags字段包含一個數組,其中至少一個元素與“ appliances”或“ school”匹配。

db.inventory.update(
  { tags: { $in: ["appliances", "school"] } },
  { $set: { sale:true } }
)

在user3939059的情況下,查詢將如下所示:

ids = ['123', '456', '234', '534']
tags = ['Tag1', 'Tag2', 'Tag3']

pb_db.db.collection.find({"ID": {$in: ids}, "Tag": {$in: tags}}, {'ID': 1, 'Tag': 1, 'Name': 1, '_created_at': 1})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM