Ad
Unable To Fetch Data Based On Boolean Value In Mongodb
I'm having JSON data in mongo and I want to fetch only those domains where activeInd=true from an array. Below is the sample data in the DB I have.
{
"organizationId" : 339975,
"domains" : [
{
"application" : "ABC",
"activeInd": true,
"subdomain":["URL1","url2"]
},
{
"application" : "mno",
"activeInd": false,
"subdomain":["URL3","url4"]
},
{
"application" : "pqr",
"activeInd": false,
"subdomain":["URL","url6"]
},
{
"application" : "egh",
"activeInd": true,
"subdomain":["URL11","url16"]
}]
}
And I have tried some solutions like below
db.collectionName.aggregate([{$project: {organizationId: {$eq: ["$organizationId", 339975]},
domains:{
$filter: {
input: "$domains",
as : "domains",
cond: {$eq: ["$$domains.activeInd", true]}
}
}}
}])
This is fetching data from organizationId as well but my requirement is in the given organizationId the domains should be fetched where activeInd=true In general i need output like below sample Required output
{
"organizationId" : 339975,
"domains" : [
{
"application" : "ABC",
"activeInd": true,
"subdomain":["URL1","url2"]
},
{
"application" : "egh",
"activeInd": true,
"subdomain":["URL11","url16"]
}]
}
Can someone help me please.
Ad
Answer
Maybe $filter as follow:
db.collection.aggregate([
{
$match: {
organizationId: 339975
}
},
{
$project: {
domains: {
$filter: {
input: "$domains",
as: "item",
cond: {
$eq: [
"$$item.activeInd",
true
]
}
}
}
}
}
])
explained:
- In the match stage you fetch only the necessary organizationId documents
- In the filter stage you get only the activeInd items from domains
Ad
source: stackoverflow.com
Related Questions
- → How to Use MySQL and MongoDb together
- → GET user info from MongoDB w/AJAX
- → Advanced elasticsearch query
- → Cannot conduct multiple queries based on values within array?
- → how to replace ObjectId in JavaScript with Epoch Time
- → Meteor: Iterating over an Object inside of a Collection
- → use mongoDB ObjectID in query parameter, does it affect SEO?
- → Indirect Modification of Overloaded Property Laravel MongoDB
- → Large quantity of data real time visualization
- → How to make and store slug for post title?
- → Exception in Mongo write when removing multiple documents
- → Passport.js serializeUser and desializeUser are not being called ever?
- → How to add data to an already existing item in mongodb
Ad