Need to filter mongo documents on a field only if that field exists in that document

Viewed 248

I have a collection with documents each having its own set of columns. There are few columns that will occur in all documents and few that wont. Need to build a query that searches for a text within a column only if that column exist

Example : In the collections article: db.articles.find({}, {Title:1,Conclusions:1})

    { "_id" : ObjectId("5c392c930e7c0058e781a2c4"), "Title" : "Title for article1", "Conclusions" : { "Conclusions" : "Some conclusion" } }
    { "_id" : ObjectId("5c392c930e7c0058e781a2c9"), "Title" : "Title for article2" }
    { "_id" : ObjectId("5c392c930e7c0058e781a2ce"), "Title" : "Title for article3" }
    { "_id" : ObjectId("5c392c940e7c0058e781a2d8"), "Title" : "Title for article4", "Conclusions" : { "Conclusions" : "Some other conclusion" } }

I am able to check if the column exist with the below:

    db.articles.find({ "Conclusions": { $exists: true, $ne:null } }, {Title:1,Conclusions:1})

but not able to use it to add the 2nd condition (below returns nothing)

    db.articles.find({ "Conclusions": { $exists: true, $ne:null }, Conclusions: '/other/i' }, {Title:1,Conclusions:1})

Expected result:

    { "_id" : ObjectId("5c392c940e7c0058e781a2d8"), "Title" : "Title for article4", "Conclusions" : { "Conclusions" : "Some other conclusion" } }
0 Answers
Related