How to Check Whether a Field Exists or Not in Mongodb

Check that Field Exists with MongoDB

Use $ne (for "not equal")

db.collection.find({ "fieldToCheck": { $ne: null } })

Mongodb check If field exists in an sub-document of an array

You problems come from a misconception about data modeling in MongoDB, not uncommon for developers coming from other DBMS. Let me illustrate this with the example of how data modeling works with an RDBMS vs MongoDB (and a lot of the other NoSQL databases as well).

With an RDBMS, you identify your entities and their properties. Next, you identify the relations, normalize the data model and bang your had against the wall for a few to get the UPPER LEFT ABOVE AND BEYOND JOIN™ that will answer the questions arising from use case A. Then, you pretty much do the same for use case B.

With MongoDB, you would turn this upside down. Looking at your use cases, you would try to find out what information you need to answer the questions arising from the use case and then model your data so that those questions can get answered in the most efficient way.

Let us stick with your example of a contacts database. A few assumptions to be made here:

  1. Each user can have an arbitrary number of contacts.
  2. Each contact and each user need to be uniquely identified by something other than a name, because names can change and whatnot.
  3. Redundancy is not a bad thing.

With the first assumption, embedding contacts into a user document is out of question, since there is a document size limit. Regarding our second assumption: the uid field becomes not redundant, but simply useless, as there already is the _id field uniquely identifying the data set in question.

The use cases

Let us look at some use cases, which are simplified for the sake of the example, but it will give you the picture.

  1. Given a user, I want to find a single contact.
  2. Given a user, I want to find all of his contacts.
  3. Given a user, I want to find the details of his contact "John Doe"
  4. Given a contact, I want to edit it.
  5. Given a contact, I want to delete it.
The data modelsUser
{
"_id": new ObjectId(),
"name": new String(),
"whatever": {}
}
Contact
{
"_id": new ObjectId(),
"contactOf": ObjectId(),
"name": new String(),
"phone": new String()
}

Obviously, contactOf refers to an ObjectId which must exist in the User collection.

The implementations

Given a user, I want to find a single contact.

If I have the user object, I have it's _id, and the query for a single contact becomes as easy as

db.contacts.findOne({"contactOf":self._id})

Given a user, I want to find all of his contacts.

Equally easy:

db.contacts.find({"contactOf":self._id})

Given a user, I want to find the details of his contact "John Doe"

db.contacts.find({"contactOf":self._id,"name":"John Doe"})

Now we have the contact one way or the other, including his/her/undecided/choose not to say _id, we can easily edit/delete it:

Given a contact, I want to edit it.

db.contacts.update({"_id":contact._id},{$set:{"name":"John F Doe"}})

I trust that by now you get an idea on how to delete John from the contacts of our user.

Notes

Indices

With your data model, you would have needed to add additional indices for the uid fields - which serves no purpose, as we found out. Furthermore, _id is indexed by default, so we make good use of this index. An additional index should be done on the contact collection, however:

db.contact.ensureIndex({"contactOf":1,"name":1})

Normalization

Not done here at all. The reasons for this are manifold, but the most important is that while John Doe might have only have the mobile number of "Mallory H Ousefriend", his wife Jane Doe might also have the email address "janes_naughty_boy@censored.com" - which at least Mallory surely would not want to pop up in John's contact list. So even if we had identity of a contact, you most likely would not want to reflect that.

Conclusion

With a little bit of data remodeling, we reduced the number of additional indices we need to 1, made the queries much simpler and circumvented the BSON document size limit. As for the performance, I guess we are talking of at least one order of magnitude.

How to check if list of field values exists in db mongodb

You can use $in

db.collection.find({
email: {
$in: [
"email3",
"email4"
]
}
})

Working Mongo playground

Check if field exists, then compare with a value in Mongoose

As the error suggests the position of your $or is wrong you can do it like this

query.$or = [
{isDeleted: { $exists: false }},
{isDeleted: { $ne: true }}
];

return this.find(query)
.exec();

MongoDB $or reference

In your case isDeleted: Boolean but you're checking it against an Object which is {$or: []} that's why you get a type error.

How to check if the field exists and if exists, get its value in mongodb $in?

It should be something like this :

db.getCollection('YourCollectionName').find({$and :[{field1: {$in:[1234567, 7654321]}},{field2:{$exists: true}}]},
{field1:1, field2:1, _id:0})

Your query has syntax errors & also $and is an array that takes in multiple filters, which has to be given in place of filterQuery of .find() . Ex :- .find(filterQuery, projectQuery)

MongoDB find documents with a field not empty, IF EXISTS

Query1

  • find solution
  • keep document if field is missing or its not empty string

Playmongo

find({"$or": 
[{"client_comment": {"$exists": false}}, {"client_comment": {"$ne": ""}}]})

Query2

  • aggregate solution
  • keep document if field is missing or its not empty string

Playmongo

aggregate(
[{"$match":
{"$expr":
{"$or":
[{"$eq": [{"$type": "$client_comment"}, "missing"]},
{"$ne": ["$client_comment", ""]}]}}}])

Mongodb- Query to check if a field in the json array exists or not

You can use $elemMatch to evaluate the presence of the nested key. Once that's accomplished, project out the _id value.

db.orders.find({
orderItems: {
$elemMatch: {
"isEligible": {
$exists: false
}
}
}
},
{
_id: 1
})

Here is a Mongo playground with the finished code, and a similar SO answer.

Find all docs where field doesn't exists, plus if field exists apply condition

How about something like this:

db.stackoverflow.find({
$or: [
{ howmuch: { $exists:false } },
{ howmuch:5 }
]})

In the stackoverflow collection, this will find all documents that do not have the howmuch field plus all documents that do have howmuch set to 5.



Related Topics



Leave a reply



Submit