D
D
Di2022-01-23 10:23:37
Python
Di, 2022-01-23 10:23:37

How to display the desired field from the cursor (pymongo)?

I'm trying to organize the output of a field from a random collection document. This code compiles without errors, but I need to modify it so that a specific field is retrieved from list(cursor) and displayed. I read the documentation but couldn't find a solution, how to implement this?

@client.command()
async def one(ctx):
    db = cluster['dbname']
    collection = db['collname']
    cursor = db.collection.aggregate([{ "$sample" : {"size" : 1}}])
    doc = list(cursor)
    await ctx.send(f’Output: {doc}’)


I tried to implement a dictionary access through ["field_name"] after aggregation:
@client.command()
async def one(ctx):
    db = cluster['dbname']
    collection = db['collname']
    cursor = egeinf1.aggregate([{ "$sample" : {"size" : 1}}])["field_name"]
    await ctx.send(embed = discord.Embed(description = f"{cursor}"))

Gives an error: TypeError: 'CommandCursor' object is not subscriptable
I read a lot of articles, I still don't know how to fix it
Please help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
ya_ne_znau, 2022-01-23
@Pr0sto_Danya

Try this: https://docs.mongodb.com/manual/reference/operator...
In theory:

db.collection.aggregate([
    {"$sample": {"size": 1}},
    {"$project": {
        "_id": 0,
        "<field>": <1 или "$_id.<field>" (не знаю)>
    }}
])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question