Return id based on existence of multiple value in mongodb - mongodb

I want to return id based on certain condition like if a user value doesnot exist and both phone and email field matches with search condition with no available userId then i want to get the id of that specific row.If the userid exist it will not return anything.The idea of the query something like this:
db.records.find( { userId: { $exists: false } } )
db.records.find( { phone: "A", email:"B" }, { id: 1} )
how can i merge this query into one and return the only id in mongodb

You can add the queries with commas:
db.records.find( { userId: { $exists: false },phone: "A", email:"B" }, { id: 1} )
Here's an example:
https://mongoplayground.net/p/V_HL7WQqoiO

Related

update Object inside array of Object with mongoose

I'm trying to update and object inside array in MongoDB.
my model is:
let userSchema = new mongoose.Schema({
userName: {
type: String
},
password: {
type: String
},
history: []
});
And inside history each element is from the next type:
id, array(named ing_array) and boolean field called favorite.
I'm trying to update the favorite field with mongoose with the userName and the id.
I tried to do this query and I didn't succed.
Could some one tell me whats worng?
[object photo]: https://i.stack.imgur.com/2mYpP.png
User.findOneAndUpdate(
{ "userName": user_name, "history.id": id },
{ "$set": { "history.$.favorite": true }}
);
You have to use arrayFilters in this way:
db.collection.update({
"userName": "uname",
"history.id": 1
},
{
"$set": {
"history.$[element].favorite": false
}
},
{
"arrayFilters": [
{
"element.id": 1
}
]
})
Note that update query has the format: update(query, update, options) (Check the docs).
When you do { "userName": user_name, "history.id": id } you are telling mongo "Give me all documents where userName is user_name and array history has an id with value id. This return all history array because it belows to the document.
To update an specific object into the array is neccessary to use arrayFilters to tell mongo which object do you want to update. In this case the object where id is equal to 1. You can use as you want to match wit your requirements.
Example here

mongodb find and update one with multiple conditions

{
roomId: "id",
questions:{
q1:{
user1:"user1's work"
}
}
}
I'm trying to query mongodb with multiple conditions, that roomId has to match, and questions must be q1, and in q1 there must be a user1.
Here's what I've tried so far. Using and operator, but doesn't seems to work.For now I'm using find, as I read in the docs that updateMany has the same query selector as find.
const result = await collection.find({
$and: [
{
roomId: roomId,
},
{
questions: {
currentQuestion: {
userName,
},
},
},
],
});
My schema:
{
roomId: "id",
roomName:"roomName",
questions:{
question1:{
user1:"user1's work",
userN: "userN's work"
},
questionN:{
user1:"",
userN:""
}
}
}
My expected input , (roomId, currentQuestion, userName) for query conditions,"userWork" to be inserted to what's under userName (user1 - userN).
Expected output, that the user's work gets updated with "userWork", under the right room, right currentQuestion and the right user.
You need this query I think:
db.collection.find({
"roomId": "id",
"questions.q1.user1": {
$exists: true
}
})
This query find a roomId which match your 'id' and then, check if exists the element questions.q1.user1.
Mongo playground example here
PS: You said update but... what do you want to update?
Assuming your schema is like
{
roomId: "id",
questions: {
q1: {
user1: "user1's work",
currentQuestion: "currentQuestion1"
}
}
}
Then, the query to update the currentQuestion field whose match the id and has existing questions.q1.user1 is this:
db.collection.update({
"roomId": "id",
"questions.q1.user1": {
$exists: true
}
},
{
"$set": {
"questions.q1.currentQuestion": "new question"
}
})
Example here
Note that if currentQuestion is one level up, you only have to modify $set object.
If you are not asking for this, please provide a complete schema, example input and expected output.

MongoDB Regex $and $or Search Query

I am trying to construct a query that will accept multiple fields that can be searched over using regex for partial field matching that also has a hard constraint on other fields.
Example:
Collection: "Projects"
Required Information: { propertyId: "abc", clientId: "xyz" }
Fields to be Searched: name, serviceType.name, manager.name
Currently, I have a query like this, but if there are no results it returns all the results, which isn't helpful.
{
'$and': [
{ propertyId: '7sHGCHT4ns6z9j6BC' },
{ clientId: 'xyz' },
{ '$or':
[
{ name: /HVAC/gi },
{ 'serviceType.name': /HVAC/gi },
{ 'manager.name': /HVAC/gi }
]
}
]
}
If anyone has any insight into this it would be much appreciated.
Example Document:
{
_id: "abc",
propertyId: "7sHGCHT4ns6z9j6BC",
clientId: "xyz"
name: "16.000.001",
serviceType: {
_id: "asdf",
name: "HVAC"
},
manager: {
_id: "dfgh",
name: "Patrick Lewis",
}
}
The expected result is to only find documents where propertyId = 7sHGCHT4ns6z9j6BC AND one at least one of the following keys: name, serviceType.name, or manager.name match an inputted string, in this case, it's HVAC and if none of the regex fields match, then return nothing.
UPDATE
The issue was with MongoDB, after restarting it, everything worked.
Try following script:
db.collection.find({
$and:[
{propertyId:"7sHGCHT4ns6z9j6BC"},
{
$or:[
{name: /HVAC/i},
{"serviceType.name": /HVAC/i},
{"manager.name": /HVAC/i}
]
}]
})
Query above will return a document or documents if and only if propertyId matches and either of name, serviceType.name or manager.name matches desired regex.

Checking for similar records in mongodb across multiple fields.

In mongodb, I have a collection of people with the schema below. I need to write an aggregation to find possible duplicates in the database by checking:
If another person with same firstName, lastName & currentCompany exists.
Or, if another person with the same currentCompany & currentTitle exists.
Or, if another person has the same email (which is stored as an object in an array)
Or, if someone else has the same linkedIn/twitter url.
Is there a straightforward way of checking for duplicates based on the above cases w/ a mongodb aggregation? This question is close to what I'm looking for, but I need to check more than just one key/value.
{ _id: 'wHwNNKMSL9v3gKEuz',
firstName: 'John',
lastName: 'Doe',
currentCompany: 'John Co',
currentTitle: 'VP Sanitation',
emails:
[ { address: 'Anais.Grant#hotmail.com',
valid: true } ],
urls:
{ linkedIn: 'http://linkedin.com/johnDoe',
twitter: 'http://twitter.com/#john',
}
}
Thanks!
We can achieve it is using the following
$and, $or, $ne.
Note:- You need to feed one record as input for the conditions to match it with other records for eliminating the duplicates
I have given a sample query which will be filtering your collection for these two criterias, you can add the rest of your conditions to get the final result
If another person with same firstName, lastName & currentCompany exists.
Or, if someone else has the same linkedIn/twitter url.
db.yourcollection.find({
$and: [{
$or: [{
firstName: {
$ne: 'John'
}
}, {
lastName: {
$ne: 'Doe'
}
}, {
currentCompany: {
$ne: 'John Co'
}
}]
}, {
$or: [{
"urls.linkedIn": {
$ne: 'http://linkedin.com/Doe'
}
}]
}]
})

JugglingDB MongoDB Array of IDs

I'm using MongoDB adapter of Juggling-DB.
How can I run the equivalent of the following SQL query (IDs are fake)
SELECT * FROM APPS
WHERE
active = 1
AND (
user_id = '12345'
OR
id IN ('456', '789', '012')
)
that is "active apps that either belong to the given user or are available to all".
I tried the following:
{
where: {
active: true,
or: [
{
user_id: '12345'
},
{
_id: {
in: ['456', '789', '012']
}
}
]
}
}
But it returns nothing. Looking at the source code my wild guess is that it only converts strings to MongoDB.ObjectID when _id is a single string, not an array.
The mongodb query should be like:
db.apps.find({active: true, "$or": [{"user_id": "12345"}, {"_id": { $in: ['1', '2', '3']}}]})