Generating Combinations in MongoDB

Asked 2 years ago, Updated 2 years ago, 92 views

An array of arrays of all combinations of elements = 5 (e.g., 1, 2, ..., 20) is formed by extracting arbitrary three elements from an array 1 and arbitrary two elements (no duplication) from an array 2 with array length 長 5 (e.g., [1, 2, 3, 21, 22].SQL has found some examples of combinations (no duplication) on the Internet, but what kind of query should I write if I do this with MongoDB?
Of course, it would be better to run as fast as possible.

mongodb

2022-09-30 19:53

1 Answers

MongoDB has normal sorting and filtering capabilities as well as Aggregation and Map/Reduce frameworks, but does not support merging (server-side collections or arrays).

If MongoDB is used as a persistent storage device, read all objects in the client application and run its permutation algorithm.

Python examples:

import pymongo

from itertools import permutations

dbconn=pymongo.MongoClient("localhost", 27017)
mycol=dbconn["my_db"]["my_collection"]
doc = mycoll.find_one({"_id":10001})
# doc ["a"] = [1, 3, 5, 7]
# doc ["b"] = [2, 4, 6]
aa = [ ]
for ap in permutations (doc["a", 3):
    for bp in permutations (doc["b"], 2):
        print(ap+bp)
        aa.append(ap+bp)

#(1, 3, 5, 2, 4)
#(1, 3, 5, 2, 6)
#(1, 3, 5, 4, 2)
#.....
#(7, 5, 3, 4, 6)
#(7, 5, 3, 6, 2)
#(7, 5, 3, 6, 4)

print(len(aa))
#144


2022-09-30 19:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.