Querying ListField in a MongoDB Subdocument
Usually a MongoDB ListField wraps multiple fields in strings. This storage mode makes easy management. Users don’t need to worry about the alignment between detailed data and fields when importing and exporting a large volume of data. So that’s fast. On the other hand, however, you need to split the strings and perform data type conversion before real data processing. It’s inconvenient to handle this with mongo shell. Yet it’s easy to get it done in esProc SPL that provides a series of interface functions.
Collection Cbettwen contains multilevel subdocuments. dataList field contains strings of List data type. Each string is made up of a set of numbers. Task: find the string where the first number is greater than 6154 and equal to and less than 6155.
Here’s one of the subdocument in Cbettwen:
{ |
The eligible string is "6154.5,37.9,1.529,1.429,1.429","6155,30.4,1.505,1.532,1.543".
SPL script:
A |
|
1 |
=mongo_open("mongodb:// localhost:27017/local?user=test&password=test") |
2 |
=mongo_shell(A1,"Cbettwen.find(,{_id:0})") |
3 |
=A2.conj((t=~.objList.data.dataList.new(~),t.select((s=float(#1.split@c()(1)),s>6154 && s<=6155)))) |
4 |
=A3.fetch() |
5 |
=mongo_close(A1) |
A1: Connect to MongoDB database. The connection string is mongo://ip:port/db?arg=value&….
A2: find() function retrieves documents from collection Cbettwen and return result as a cursor. As no filtering condition is specified, it gets all fields except _id.
A3: Find out the eligible string. conj() function concatenates results of processing each document in A2; ~ represents a member in the table sequence of one level higher. new() function creates a new table sequence; #1 represents the first field in the table sequence. split() function splits strings by commas and return them as a sequence; @1 option enables splitting strings into a two-member sequence by the first separator; s enables conversion of the first string into a float type number for comparison.
A4: Batch process data in A3’s cursor to get a result and store it in the memory:
6154.5,37.9,1.529,1.429,1.429 |
6155,30.4,1.505,1.532,1.543 |
6154.6,100.9,1.529,1.429,1.429 |
6154.7,200.9,1.529,1.429,1.429 |
6155,100.3,1.49,1.436,1.462 |
6155,200.3,1.49,1.436,1.462 |
6154.6,300.9,1.529,1.429,1.429 |
6154.7,400.9,1.529,1.429,1.429 |
6155,300.3,1.49,1.436,1.462 |
6155,400.3,1.49,1.436,1.462 |
6154.6,500.9,1.529,1.429,1.429 |
6154.7,600.9,1.529,1.429,1.429 |
6155,500.3,1.49,1.436,1.462 |
A5: Close MongoDB connection.
It’s concise and easy to query MongoDB ListField in SPL.
SPL Official Website 👉 https://www.scudata.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProc_SPL
SPL Learning Material 👉 https://c.scudata.com
SPL Source Code and Package 👉 https://github.com/SPLWare/esProc
Discord 👉 https://discord.gg/cFTcUNs7
Youtube 👉 https://www.youtube.com/@esProc_SPL
Chinese version