Can the $in operator return null for unmatched documents? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How do I update/upsert a document in Mongoose?Query for documents where array size is greater than 1Find document with array that contains a specific valuemongodb: return an array of document idsHow do you query a MongoDB document where an array attribute is null or of zero length?Mongoose: findOneAndUpdate doesn't return updated documentMongoDB- Return Array of existing fields by compare collection with Array of objectmongoose findall return data from a different modelChecking that a field in Mongo contains multiple valuesHow to modify existing data or create new if doesn't exist in mongodb?

Why is one lightbulb in a string illuminated?

Compiling and throwing simple dynamic exceptions at runtime for JVM

Is my guitar’s action too high?

Does the Pact of the Blade warlock feature allow me to customize the properties of the pact weapon I create?

Can I take recommendation from someone I met at a conference?

Why did Israel vote against lifting the American embargo on Cuba?

Converting a text document with special format to Pandas DataFrame

/bin/ls sorts differently than just ls

Is Vivien of the Wilds + Wilderness Reclamation a competitive combo?

What is the difference between 准时 and 按时?

What's the connection between Mr. Nancy and fried chicken?

Why aren't road bike wheels tiny?

tabularx column has extra padding at right?

What helicopter has the most rotor blades?

How do I deal with an erroneously large refund?

Can the van der Waals coefficients be negative in the van der Waals equation for real gases?

Can this water damage be explained by lack of gutters and grading issues?

Why are two-digit numbers in Jonathan Swift's "Gulliver's Travels" (1726) written in "German style"?

Should man-made satellites feature an intelligent inverted "cow catcher"?

What were wait-states, and why was it only an issue for PCs?

Recursive calls to a function - why is the address of the parameter passed to it lowering with each call?

Trying to enter the Fox's den

Is Bran literally the world's memory?

false 'Security alert' from Google - every login generates mails from 'no-reply@accounts.google.com'



Can the $in operator return null for unmatched documents?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How do I update/upsert a document in Mongoose?Query for documents where array size is greater than 1Find document with array that contains a specific valuemongodb: return an array of document idsHow do you query a MongoDB document where an array attribute is null or of zero length?Mongoose: findOneAndUpdate doesn't return updated documentMongoDB- Return Array of existing fields by compare collection with Array of objectmongoose findall return data from a different modelChecking that a field in Mongo contains multiple valuesHow to modify existing data or create new if doesn't exist in mongodb?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I have a requirement to return the same length of the array provided to mongo.



usernames = ['user1', 'user2', 'user3']



Now lets say user3 doesn't exist, is there a way to return null when mongo doesn't find the document ?



If i'm using the $in operator i only get the matched documents ex.



User.find( username: $in: usernames )



result = [user1Document, user2Document]



I can loop over the array and query the database for every username but it's not efficient.



const userPromises = usernames.map(username => User.findOne( username ));
return Promise.all(userPromises);









share|improve this question

















  • 1





    You should use iteration to return null for the non-existing elements as you did. Aggregation trick might help here but it is even more costly then the looping.

    – Anthony Winzlet
    Mar 22 at 14:24

















1















I have a requirement to return the same length of the array provided to mongo.



usernames = ['user1', 'user2', 'user3']



Now lets say user3 doesn't exist, is there a way to return null when mongo doesn't find the document ?



If i'm using the $in operator i only get the matched documents ex.



User.find( username: $in: usernames )



result = [user1Document, user2Document]



I can loop over the array and query the database for every username but it's not efficient.



const userPromises = usernames.map(username => User.findOne( username ));
return Promise.all(userPromises);









share|improve this question

















  • 1





    You should use iteration to return null for the non-existing elements as you did. Aggregation trick might help here but it is even more costly then the looping.

    – Anthony Winzlet
    Mar 22 at 14:24













1












1








1


0






I have a requirement to return the same length of the array provided to mongo.



usernames = ['user1', 'user2', 'user3']



Now lets say user3 doesn't exist, is there a way to return null when mongo doesn't find the document ?



If i'm using the $in operator i only get the matched documents ex.



User.find( username: $in: usernames )



result = [user1Document, user2Document]



I can loop over the array and query the database for every username but it's not efficient.



const userPromises = usernames.map(username => User.findOne( username ));
return Promise.all(userPromises);









share|improve this question














I have a requirement to return the same length of the array provided to mongo.



usernames = ['user1', 'user2', 'user3']



Now lets say user3 doesn't exist, is there a way to return null when mongo doesn't find the document ?



If i'm using the $in operator i only get the matched documents ex.



User.find( username: $in: usernames )



result = [user1Document, user2Document]



I can loop over the array and query the database for every username but it's not efficient.



const userPromises = usernames.map(username => User.findOne( username ));
return Promise.all(userPromises);






mongodb mongoose






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 22 at 14:11









Asaf AvivAsaf Aviv

1,1031213




1,1031213







  • 1





    You should use iteration to return null for the non-existing elements as you did. Aggregation trick might help here but it is even more costly then the looping.

    – Anthony Winzlet
    Mar 22 at 14:24












  • 1





    You should use iteration to return null for the non-existing elements as you did. Aggregation trick might help here but it is even more costly then the looping.

    – Anthony Winzlet
    Mar 22 at 14:24







1




1





You should use iteration to return null for the non-existing elements as you did. Aggregation trick might help here but it is even more costly then the looping.

– Anthony Winzlet
Mar 22 at 14:24





You should use iteration to return null for the non-existing elements as you did. Aggregation trick might help here but it is even more costly then the looping.

– Anthony Winzlet
Mar 22 at 14:24












1 Answer
1






active

oldest

votes


















1














You can start with initial filtering using $in and then to map all the values from input array into final result you have to $group them $push-ing $$ROOT (enitre document), then you can just merge input usernames with docs using $map and $filter operators:



db.col.aggregate([

$match: username: $in: ['user1', 'user2', 'user3']
,

$group:
_id: null,
docs: $push: "$$ROOT"

,

$project:
_id: 0,
results:
$map:
input: ['user1', 'user2', 'user3'],
as: 'username',
in:
$let:
vars:
filtered:
$filter:
input: "$docs",
as: "doc",
cond: $eq: [ "$$doc.username", "$$username" ]


,
in:
$arrayElemAt: [ "$$filtered", 0 ]







])


Mongo playground






share|improve this answer























  • Perfect, Thank you!

    – Asaf Aviv
    Mar 22 at 14:42











  • How can i do the same operation with ObjectIds ? when i try to change username to _id i'm getting '_id' starts with an invalid character for a user variable name

    – Asaf Aviv
    Mar 22 at 15:19












  • @AsafAviv yes you can but I need to see your code to see why you're getting that error, please use mongo playground for that

    – mickl
    Mar 22 at 17:17











  • mongoplayground.net/p/Zep8U4aeKHx thanks again

    – Asaf Aviv
    Mar 22 at 17:50






  • 1





    Nice, Thank you for your time @mickl i appreciate it!

    – Asaf Aviv
    Mar 22 at 18:08











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55301492%2fcan-the-in-operator-return-null-for-unmatched-documents%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














You can start with initial filtering using $in and then to map all the values from input array into final result you have to $group them $push-ing $$ROOT (enitre document), then you can just merge input usernames with docs using $map and $filter operators:



db.col.aggregate([

$match: username: $in: ['user1', 'user2', 'user3']
,

$group:
_id: null,
docs: $push: "$$ROOT"

,

$project:
_id: 0,
results:
$map:
input: ['user1', 'user2', 'user3'],
as: 'username',
in:
$let:
vars:
filtered:
$filter:
input: "$docs",
as: "doc",
cond: $eq: [ "$$doc.username", "$$username" ]


,
in:
$arrayElemAt: [ "$$filtered", 0 ]







])


Mongo playground






share|improve this answer























  • Perfect, Thank you!

    – Asaf Aviv
    Mar 22 at 14:42











  • How can i do the same operation with ObjectIds ? when i try to change username to _id i'm getting '_id' starts with an invalid character for a user variable name

    – Asaf Aviv
    Mar 22 at 15:19












  • @AsafAviv yes you can but I need to see your code to see why you're getting that error, please use mongo playground for that

    – mickl
    Mar 22 at 17:17











  • mongoplayground.net/p/Zep8U4aeKHx thanks again

    – Asaf Aviv
    Mar 22 at 17:50






  • 1





    Nice, Thank you for your time @mickl i appreciate it!

    – Asaf Aviv
    Mar 22 at 18:08















1














You can start with initial filtering using $in and then to map all the values from input array into final result you have to $group them $push-ing $$ROOT (enitre document), then you can just merge input usernames with docs using $map and $filter operators:



db.col.aggregate([

$match: username: $in: ['user1', 'user2', 'user3']
,

$group:
_id: null,
docs: $push: "$$ROOT"

,

$project:
_id: 0,
results:
$map:
input: ['user1', 'user2', 'user3'],
as: 'username',
in:
$let:
vars:
filtered:
$filter:
input: "$docs",
as: "doc",
cond: $eq: [ "$$doc.username", "$$username" ]


,
in:
$arrayElemAt: [ "$$filtered", 0 ]







])


Mongo playground






share|improve this answer























  • Perfect, Thank you!

    – Asaf Aviv
    Mar 22 at 14:42











  • How can i do the same operation with ObjectIds ? when i try to change username to _id i'm getting '_id' starts with an invalid character for a user variable name

    – Asaf Aviv
    Mar 22 at 15:19












  • @AsafAviv yes you can but I need to see your code to see why you're getting that error, please use mongo playground for that

    – mickl
    Mar 22 at 17:17











  • mongoplayground.net/p/Zep8U4aeKHx thanks again

    – Asaf Aviv
    Mar 22 at 17:50






  • 1





    Nice, Thank you for your time @mickl i appreciate it!

    – Asaf Aviv
    Mar 22 at 18:08













1












1








1







You can start with initial filtering using $in and then to map all the values from input array into final result you have to $group them $push-ing $$ROOT (enitre document), then you can just merge input usernames with docs using $map and $filter operators:



db.col.aggregate([

$match: username: $in: ['user1', 'user2', 'user3']
,

$group:
_id: null,
docs: $push: "$$ROOT"

,

$project:
_id: 0,
results:
$map:
input: ['user1', 'user2', 'user3'],
as: 'username',
in:
$let:
vars:
filtered:
$filter:
input: "$docs",
as: "doc",
cond: $eq: [ "$$doc.username", "$$username" ]


,
in:
$arrayElemAt: [ "$$filtered", 0 ]







])


Mongo playground






share|improve this answer













You can start with initial filtering using $in and then to map all the values from input array into final result you have to $group them $push-ing $$ROOT (enitre document), then you can just merge input usernames with docs using $map and $filter operators:



db.col.aggregate([

$match: username: $in: ['user1', 'user2', 'user3']
,

$group:
_id: null,
docs: $push: "$$ROOT"

,

$project:
_id: 0,
results:
$map:
input: ['user1', 'user2', 'user3'],
as: 'username',
in:
$let:
vars:
filtered:
$filter:
input: "$docs",
as: "doc",
cond: $eq: [ "$$doc.username", "$$username" ]


,
in:
$arrayElemAt: [ "$$filtered", 0 ]







])


Mongo playground







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 22 at 14:23









micklmickl

16.4k61841




16.4k61841












  • Perfect, Thank you!

    – Asaf Aviv
    Mar 22 at 14:42











  • How can i do the same operation with ObjectIds ? when i try to change username to _id i'm getting '_id' starts with an invalid character for a user variable name

    – Asaf Aviv
    Mar 22 at 15:19












  • @AsafAviv yes you can but I need to see your code to see why you're getting that error, please use mongo playground for that

    – mickl
    Mar 22 at 17:17











  • mongoplayground.net/p/Zep8U4aeKHx thanks again

    – Asaf Aviv
    Mar 22 at 17:50






  • 1





    Nice, Thank you for your time @mickl i appreciate it!

    – Asaf Aviv
    Mar 22 at 18:08

















  • Perfect, Thank you!

    – Asaf Aviv
    Mar 22 at 14:42











  • How can i do the same operation with ObjectIds ? when i try to change username to _id i'm getting '_id' starts with an invalid character for a user variable name

    – Asaf Aviv
    Mar 22 at 15:19












  • @AsafAviv yes you can but I need to see your code to see why you're getting that error, please use mongo playground for that

    – mickl
    Mar 22 at 17:17











  • mongoplayground.net/p/Zep8U4aeKHx thanks again

    – Asaf Aviv
    Mar 22 at 17:50






  • 1





    Nice, Thank you for your time @mickl i appreciate it!

    – Asaf Aviv
    Mar 22 at 18:08
















Perfect, Thank you!

– Asaf Aviv
Mar 22 at 14:42





Perfect, Thank you!

– Asaf Aviv
Mar 22 at 14:42













How can i do the same operation with ObjectIds ? when i try to change username to _id i'm getting '_id' starts with an invalid character for a user variable name

– Asaf Aviv
Mar 22 at 15:19






How can i do the same operation with ObjectIds ? when i try to change username to _id i'm getting '_id' starts with an invalid character for a user variable name

– Asaf Aviv
Mar 22 at 15:19














@AsafAviv yes you can but I need to see your code to see why you're getting that error, please use mongo playground for that

– mickl
Mar 22 at 17:17





@AsafAviv yes you can but I need to see your code to see why you're getting that error, please use mongo playground for that

– mickl
Mar 22 at 17:17













mongoplayground.net/p/Zep8U4aeKHx thanks again

– Asaf Aviv
Mar 22 at 17:50





mongoplayground.net/p/Zep8U4aeKHx thanks again

– Asaf Aviv
Mar 22 at 17:50




1




1





Nice, Thank you for your time @mickl i appreciate it!

– Asaf Aviv
Mar 22 at 18:08





Nice, Thank you for your time @mickl i appreciate it!

– Asaf Aviv
Mar 22 at 18:08



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55301492%2fcan-the-in-operator-return-null-for-unmatched-documents%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript