Search code examples
pythonmongodbpymongo

How work with nested field and list array


I wrote a small script that checks a field in the MongoDB collection that is duplicated and displays its value and the number of duplicates. And it works fine with fields without a dot, i.e. not with nested fields. But as soon as a nested field appears in the input data, I cannot get its value. I get 'null'. I see where the problem is. It is in the aggregation data processing cycle. The aggregation itself gives the correct data.

Here is a piece of code:

     n=0
     arc = []
     for doc in result:
             if doc["count"] > 1:
                 n=1
                 if "." in args.field:
                     arc.append({args.field: doc.get(f'"{args.field}"'), "count": doc["count"]})
                 else:
                     arc.append({args.field: doc.get(args.field), "count": doc["count"]})

This is after trying several options to solve the problem. Initially it was like this:

     n=0
     arc = []
     for doc in result:
             if doc["count"] > 1:
                 n=1
                 arc.append({args.field: doc[args.field]), "count": doc["count"]})

Solution

  • I fixed my problem. In my aggregation in Mongo I simple changed field name on name "value" and that's all.