I have following documents:
{
usera:{
data: {
order1: "data",
order2: "data2",
order3: "data3",
}
},
userb:{
data: {
order1: "data",
order2: "data2",
}
},
userc:{
data: {
order1: "data",
order3: "data3",
}
},
userd:{
data: {
order1: "data",
order2: "data2",
order3: "data3",
}
},
usere:{
data: {
order1: "data"
}
}
}
I want to query documents which has only order1
and no other order2
or other documents are available.
For example only usere
is a document that has order1 and others do not exists.
Is there anyway, where I can check length of my data
field and if it is 1 and order1
$exists
is true
CodePudding user response:
I think the below code is what you are looking for
db.collection.aggregate([
{
"$match": {
"$expr": {
"$eq": [
{
"$let": {
"vars": {
"orderElem": {
"$objectToArray": "$user.data"
},
},
"in": "$$orderElem.k"
},
},
[
"order1"
],
],
}
},
}
])