Let me explain the data I’m working on:
- The collection
properties
contains attributes for items (e.g. “main subject”, “language”, “publication date”, “publisher”). The fieldid
matches the regular expressionP[0-9]+
. - The collection
items
mainly contains literary works (e.g. academic books). The fieldid
matches the regular expressionQ[0-9]+
. The fieldstatements
is a dictionary where the keys are theid
of itmes in the collectionproperties
.
Here’s a minimal working example:
db.properties.deleteMany({})
db.properties.insertMany([{'id': 'P1', 'label': 'main subject'}])
db.properties.insertMany([{'id': 'P2', 'label': 'language of work'}])
db.items.deleteMany({});
db.items.insertMany([
{'id': 'Q1', 'label': 'algorithm'},
{'id': 'Q2', 'label': 'C++'},
{'id': 'Q3', 'label': 'English'},
{
'id': 'Q4',
'label': 'Algorithms in C++',
'statements': {
'P1': [
{'property': 'P1', 'value': 'Q1'},
{'property': 'P1', 'value': 'Q2'}
],
'P2': [
{'property': 'P2', 'value': 'Q3'}
]
}
},
]);
print('properties')
printjson(db.properties.find({}))
print('items')
printjson(db.items.find({}))
properties
[
{
_id: ObjectId('66b4f9031669d5840e2202d8'),
id: 'P1',
label: 'main subject'
},
{
_id: ObjectId('66b4f9031669d5840e2202d9'),
id: 'P2',
label: 'language of work'
}
]
items
[
{
_id: ObjectId('66b4f9031669d5840e2202da'),
id: 'Q1',
label: 'algorithm'
},
{
_id: ObjectId('66b4f9031669d5840e2202db'),
id: 'Q2',
label: 'C++'
},
{
_id: ObjectId('66b4f9031669d5840e2202dc'),
id: 'Q3',
label: 'English'
},
{
_id: ObjectId('66b4f9031669d5840e2202dd'),
id: 'Q4',
label: 'Algorithms in C++',
statements: {
P1: [
{
property: 'P1',
value: 'Q1'
},
{
property: 'P1',
value: 'Q2'
}
],
P2: [
{
property: 'P2',
value: 'Q3'
}
]
}
}
]
I want to get the following result. That is, lookup the field property
and value
of each item in the array stored in the value of the key-value pairs in the field statements
.
I don’t know how to instruct $lookup
to iterate through all key-value pairs in the dictionary statements
. Then, iterate through all items in the array stored in the value of the key-value pairs of statements
and perform $lookup in the fields property
and value
.
[
{
_id: ObjectId('66b4f699c56a647e922202dd'),
id: 'Q4',
label: 'Algorithms in C++',
statements: {
P1: [
{
property: {'id': 'P1', 'label': 'main subject'}
value: {'id': 'Q1', 'label': 'algorithm'}
},
{
property: {'id': 'P1', 'label': 'main subject'}
value: {'id': 'Q2', 'label': 'C++'}
}
],
P2: [
{
property: {'id': 'P2', 'label': 'language'}
value: {'id': 'Q3', 'label': 'English'}
}
]
}
}
]
I searched information on the Internet, but I only found examples that showed how to perform $lookup
on explicit fields. I didn’t find examples on how to perform $lookup
on an arbitrary number of fields.