Merge MongoDB Documents in esProc

Blog 1185 0

Problem source:https://groups.google.com/forum/#!topic/mongodb-user/BpgEaRqrKsA

Below is a selection of Collection C1:

esProc_NoSQL_merge_mongodb_1

You need to group the collection by name. Each group contains the users field of the document corresponding to a same name and does not allow duplicate members. The expected result may like this:

esProc_NoSQL_merge_mongodb_2

esProc code:

  A B
1 =MongoDB(“mongo://localhost:27017/local?user=test&password=test”)
2 =A1.find(“c1″,,”{_id:0}”;”{name:1}”)
3 for A2;name =A3.(acls.read.users|acls.append.users|acls.edit.users|acls.fullControl.users)
4   =new(A3.name:_id,B3.union().id():readUsers)
5   =B2=B2|B4
6 =A1.close()  

A1: Connect to MongoDB. The connection string format is mongo://ip:port/db?arg=value&…

A2: Use find function to retrieve data from MongoDB, sort it and create a cursor. c1 is the collection name; no filtering criterion is specified; and all fields except _id will be retrieved and sorted by name. In esProc find function, which is analogous to the combination of MongoDB find, sort and limit function, the filtering criterion syntax follows the MongoDB rules.

A3: Fetch data from the cursor by loop, getting a group of documents with the same name field each time. A3’s working range is the indented B3 to B5, where A3 can be used to reference the loop variable.

B3: Retrieve all users fields from the current group of documents, as shown below:

esProc_NoSQL_merge_mongodb_4

B4: Merge users fields from all documents of the current group and remove duplicate members.

B5: Append each result of B4’s loop to B2. Finally B2 becomes this:

esProc_NoSQL_merge_mongodb_5

B2 is the final result we want. If the result is too big to be loaded into the memory, you can use export@j function in B5 to convert each of B4’s results to a JSON string and then append them to the text file one by one.

A6: Disconnect from MongoDB.

FAVOR (0)
Leave a Reply
Cancel
Icon

Hi,You need to fill in the Username and Email!

  • Username (*)
  • Email (*)
  • Website