Sort by deep document field in MongoDbSorting an array of JavaScript objects by propertySort array of objects by string property valueHow to query MongoDB with “like”?How do I drop a MongoDB database from the command line?MongoDB: How to find out if an array field contains an element?Sorting aggregation addToSet resultOrder by nested document MongodbHow to sort documents by custom (non-natural ordered) fieldquery array of sub documents to remove them in Java Spring Data Mongodb
Mixing basis sets
Is it safe to remove the bottom chords of a series of garage roof trusses?
Did the British navy fail to take into account the ballistics correction due to Coriolis force during WW1 Falkland Islands battle?
What magic extends life or grants immortality?
What is the difference between true neutral and unaligned?
What is wrong about this application of Kirchhoffs Current Law?
Why did this happen to Thanos's ships at the end of "Avengers: Endgame"?
Shouldn't the "credit score" prevent Americans from going deeper and deeper into personal debt?
Would it be possible to have a GMO that produces chocolate?
How to draw a cube that can be inscribed within a right circular cone?
Mathematical uses of string theory
Why we don't have vaccination against all diseases which are caused by microbes?
Dealing with an extrovert co-worker
Notepad++ - How to find multiple values on the same line in any permutation
Can't stopover at Sapporo when going from Asahikawa to Chitose airport?
What is the history of the university asylum law?
Why did MS-DOS applications built using Turbo Pascal fail to start with a division by zero error on faster systems?
Does travel insurance for short flight delays exist?
How to write triplets in 4/4 time without using a 3 on top of the notes all the time
Sleeping solo in a double sleeping bag
What professions would a medieval village with a population of 100 need?
Does norwegian.no airline overbook flights?
Is there a known non-euclidean geometry where two concentric circles of different radii can intersect? (as in the novel "The Universe Between")
Co-author responds to email by mistake cc'ing the EiC
Sort by deep document field in MongoDb
Sorting an array of JavaScript objects by propertySort array of objects by string property valueHow to query MongoDB with “like”?How do I drop a MongoDB database from the command line?MongoDB: How to find out if an array field contains an element?Sorting aggregation addToSet resultOrder by nested document MongodbHow to sort documents by custom (non-natural ordered) fieldquery array of sub documents to remove them in Java Spring Data Mongodb
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I have a collection called Visitor which has an array of chats and each array has a document called user.
I need to find some documents on this collection and sort them by if they have some specific user in their chats first.
The path for the user id is:chats.user._id
where:
chats // array
user // document
_id // ObjectId
The below script does sort the documents correctly, however, it expands the chats array and multiplies the document for each chat in the array.
I only need the sorting, so can I sort and not use the unwind
pipeline or make it somehow not multiply the documents?
db.getCollection('Visitor').aggregate([
$unwind: "$chats",
$match: 'event._id':ObjectId('5c942a3591deb389bfd92579'), 'chats.enabled': $exists: true,
"$project":
"_id": 1,
"chats.user._id": 1,
"weight":
"$cond": [
"$eq": [ "$chats.user._id", ObjectId("5c942a3591deb389bfd92579") ] ,
10,
0
]
,
"$sort": "weight": -1 ,
])
EDIT: I don't need to sort the inner array, but sort the find command by checking if a specific user is in the chats array.
Some sample of Visitor collection:
[
"_id" : ObjectId("5c9a3a1bd86e0ba64106e90e"),
"event" :
"_id" : ObjectId("5c942a3591deb389bfd92579")
,
"chats" : [
"enabled" : false,
"user" :
"_id" : ObjectId("5c81232f09a923b559763418")
,
"_id" : ObjectId("5c9a3a1bd86e0ba64106e915")
]
,
"_id" : ObjectId("5c9a3a35d86e0ba64106e950"),
"event" :
"_id" : ObjectId("5c942a3591deb389bfd92579")
,
"chats" : [
"enabled" : true,
"user" :
"_id" : ObjectId("5c81232f09a923b559763418")
,
"_id" : ObjectId("5c9a3a35d86e0ba64106e957")
,
"enabled" : true,
"user" :
"_id" : ObjectId("5c942a3591deb389bfd92579")
,
"_id" : ObjectId("5c9a3a34d86e0ba64106e91d")
]
]
In the above sample, I need to make the second document to be sorted first because it has the user with the _id ObjectId("5c942a3591deb389bfd92579")
.
arrays mongodb aggregation-framework
add a comment |
I have a collection called Visitor which has an array of chats and each array has a document called user.
I need to find some documents on this collection and sort them by if they have some specific user in their chats first.
The path for the user id is:chats.user._id
where:
chats // array
user // document
_id // ObjectId
The below script does sort the documents correctly, however, it expands the chats array and multiplies the document for each chat in the array.
I only need the sorting, so can I sort and not use the unwind
pipeline or make it somehow not multiply the documents?
db.getCollection('Visitor').aggregate([
$unwind: "$chats",
$match: 'event._id':ObjectId('5c942a3591deb389bfd92579'), 'chats.enabled': $exists: true,
"$project":
"_id": 1,
"chats.user._id": 1,
"weight":
"$cond": [
"$eq": [ "$chats.user._id", ObjectId("5c942a3591deb389bfd92579") ] ,
10,
0
]
,
"$sort": "weight": -1 ,
])
EDIT: I don't need to sort the inner array, but sort the find command by checking if a specific user is in the chats array.
Some sample of Visitor collection:
[
"_id" : ObjectId("5c9a3a1bd86e0ba64106e90e"),
"event" :
"_id" : ObjectId("5c942a3591deb389bfd92579")
,
"chats" : [
"enabled" : false,
"user" :
"_id" : ObjectId("5c81232f09a923b559763418")
,
"_id" : ObjectId("5c9a3a1bd86e0ba64106e915")
]
,
"_id" : ObjectId("5c9a3a35d86e0ba64106e950"),
"event" :
"_id" : ObjectId("5c942a3591deb389bfd92579")
,
"chats" : [
"enabled" : true,
"user" :
"_id" : ObjectId("5c81232f09a923b559763418")
,
"_id" : ObjectId("5c9a3a35d86e0ba64106e957")
,
"enabled" : true,
"user" :
"_id" : ObjectId("5c942a3591deb389bfd92579")
,
"_id" : ObjectId("5c9a3a34d86e0ba64106e91d")
]
]
In the above sample, I need to make the second document to be sorted first because it has the user with the _id ObjectId("5c942a3591deb389bfd92579")
.
arrays mongodb aggregation-framework
Could you show sample document from your collection ?
– mickl
Mar 27 at 16:39
added two documents where the second one should come first @mickl
– Jonathan
Mar 27 at 16:43
add a comment |
I have a collection called Visitor which has an array of chats and each array has a document called user.
I need to find some documents on this collection and sort them by if they have some specific user in their chats first.
The path for the user id is:chats.user._id
where:
chats // array
user // document
_id // ObjectId
The below script does sort the documents correctly, however, it expands the chats array and multiplies the document for each chat in the array.
I only need the sorting, so can I sort and not use the unwind
pipeline or make it somehow not multiply the documents?
db.getCollection('Visitor').aggregate([
$unwind: "$chats",
$match: 'event._id':ObjectId('5c942a3591deb389bfd92579'), 'chats.enabled': $exists: true,
"$project":
"_id": 1,
"chats.user._id": 1,
"weight":
"$cond": [
"$eq": [ "$chats.user._id", ObjectId("5c942a3591deb389bfd92579") ] ,
10,
0
]
,
"$sort": "weight": -1 ,
])
EDIT: I don't need to sort the inner array, but sort the find command by checking if a specific user is in the chats array.
Some sample of Visitor collection:
[
"_id" : ObjectId("5c9a3a1bd86e0ba64106e90e"),
"event" :
"_id" : ObjectId("5c942a3591deb389bfd92579")
,
"chats" : [
"enabled" : false,
"user" :
"_id" : ObjectId("5c81232f09a923b559763418")
,
"_id" : ObjectId("5c9a3a1bd86e0ba64106e915")
]
,
"_id" : ObjectId("5c9a3a35d86e0ba64106e950"),
"event" :
"_id" : ObjectId("5c942a3591deb389bfd92579")
,
"chats" : [
"enabled" : true,
"user" :
"_id" : ObjectId("5c81232f09a923b559763418")
,
"_id" : ObjectId("5c9a3a35d86e0ba64106e957")
,
"enabled" : true,
"user" :
"_id" : ObjectId("5c942a3591deb389bfd92579")
,
"_id" : ObjectId("5c9a3a34d86e0ba64106e91d")
]
]
In the above sample, I need to make the second document to be sorted first because it has the user with the _id ObjectId("5c942a3591deb389bfd92579")
.
arrays mongodb aggregation-framework
I have a collection called Visitor which has an array of chats and each array has a document called user.
I need to find some documents on this collection and sort them by if they have some specific user in their chats first.
The path for the user id is:chats.user._id
where:
chats // array
user // document
_id // ObjectId
The below script does sort the documents correctly, however, it expands the chats array and multiplies the document for each chat in the array.
I only need the sorting, so can I sort and not use the unwind
pipeline or make it somehow not multiply the documents?
db.getCollection('Visitor').aggregate([
$unwind: "$chats",
$match: 'event._id':ObjectId('5c942a3591deb389bfd92579'), 'chats.enabled': $exists: true,
"$project":
"_id": 1,
"chats.user._id": 1,
"weight":
"$cond": [
"$eq": [ "$chats.user._id", ObjectId("5c942a3591deb389bfd92579") ] ,
10,
0
]
,
"$sort": "weight": -1 ,
])
EDIT: I don't need to sort the inner array, but sort the find command by checking if a specific user is in the chats array.
Some sample of Visitor collection:
[
"_id" : ObjectId("5c9a3a1bd86e0ba64106e90e"),
"event" :
"_id" : ObjectId("5c942a3591deb389bfd92579")
,
"chats" : [
"enabled" : false,
"user" :
"_id" : ObjectId("5c81232f09a923b559763418")
,
"_id" : ObjectId("5c9a3a1bd86e0ba64106e915")
]
,
"_id" : ObjectId("5c9a3a35d86e0ba64106e950"),
"event" :
"_id" : ObjectId("5c942a3591deb389bfd92579")
,
"chats" : [
"enabled" : true,
"user" :
"_id" : ObjectId("5c81232f09a923b559763418")
,
"_id" : ObjectId("5c9a3a35d86e0ba64106e957")
,
"enabled" : true,
"user" :
"_id" : ObjectId("5c942a3591deb389bfd92579")
,
"_id" : ObjectId("5c9a3a34d86e0ba64106e91d")
]
]
In the above sample, I need to make the second document to be sorted first because it has the user with the _id ObjectId("5c942a3591deb389bfd92579")
.
arrays mongodb aggregation-framework
arrays mongodb aggregation-framework
edited Mar 27 at 16:48
mickl
20.3k6 gold badges20 silver badges42 bronze badges
20.3k6 gold badges20 silver badges42 bronze badges
asked Mar 27 at 16:38
JonathanJonathan
2,1577 gold badges32 silver badges52 bronze badges
2,1577 gold badges32 silver badges52 bronze badges
Could you show sample document from your collection ?
– mickl
Mar 27 at 16:39
added two documents where the second one should come first @mickl
– Jonathan
Mar 27 at 16:43
add a comment |
Could you show sample document from your collection ?
– mickl
Mar 27 at 16:39
added two documents where the second one should come first @mickl
– Jonathan
Mar 27 at 16:43
Could you show sample document from your collection ?
– mickl
Mar 27 at 16:39
Could you show sample document from your collection ?
– mickl
Mar 27 at 16:39
added two documents where the second one should come first @mickl
– Jonathan
Mar 27 at 16:43
added two documents where the second one should come first @mickl
– Jonathan
Mar 27 at 16:43
add a comment |
1 Answer
1
active
oldest
votes
The problem here is that using $unwind you modify initial structure of your documents (you will get one document per chats
. I would suggest using $map to get an array of weights based on specified userId and then you can use $max to get final weight
db.col.aggregate([
$match: 'event._id':ObjectId('5c942a3591deb389bfd92579'), 'chats.enabled': $exists: true,
"$project":
"_id": 1,
"chats.user._id": 1,
"weight":
$max: $map: input: "$chats", in: $cond: [ $eq: [ "$$this.user._id", ObjectId("5c942a3591deb389bfd92579") ] , 10, 0 ]
,
"$sort": "weight": -1 ,
])
could you add an example if there was a list users instead of one object user? Like if it was a chats array and nested users array and then some ID
– Jonathan
Mar 27 at 17:02
1
@Jonathan you need double$map
and$max
then. Please give it a try and open another question if you still need some assistance, I will try to take a look later
– mickl
Mar 27 at 17:06
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55382336%2fsort-by-deep-document-field-in-mongodb%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
The problem here is that using $unwind you modify initial structure of your documents (you will get one document per chats
. I would suggest using $map to get an array of weights based on specified userId and then you can use $max to get final weight
db.col.aggregate([
$match: 'event._id':ObjectId('5c942a3591deb389bfd92579'), 'chats.enabled': $exists: true,
"$project":
"_id": 1,
"chats.user._id": 1,
"weight":
$max: $map: input: "$chats", in: $cond: [ $eq: [ "$$this.user._id", ObjectId("5c942a3591deb389bfd92579") ] , 10, 0 ]
,
"$sort": "weight": -1 ,
])
could you add an example if there was a list users instead of one object user? Like if it was a chats array and nested users array and then some ID
– Jonathan
Mar 27 at 17:02
1
@Jonathan you need double$map
and$max
then. Please give it a try and open another question if you still need some assistance, I will try to take a look later
– mickl
Mar 27 at 17:06
add a comment |
The problem here is that using $unwind you modify initial structure of your documents (you will get one document per chats
. I would suggest using $map to get an array of weights based on specified userId and then you can use $max to get final weight
db.col.aggregate([
$match: 'event._id':ObjectId('5c942a3591deb389bfd92579'), 'chats.enabled': $exists: true,
"$project":
"_id": 1,
"chats.user._id": 1,
"weight":
$max: $map: input: "$chats", in: $cond: [ $eq: [ "$$this.user._id", ObjectId("5c942a3591deb389bfd92579") ] , 10, 0 ]
,
"$sort": "weight": -1 ,
])
could you add an example if there was a list users instead of one object user? Like if it was a chats array and nested users array and then some ID
– Jonathan
Mar 27 at 17:02
1
@Jonathan you need double$map
and$max
then. Please give it a try and open another question if you still need some assistance, I will try to take a look later
– mickl
Mar 27 at 17:06
add a comment |
The problem here is that using $unwind you modify initial structure of your documents (you will get one document per chats
. I would suggest using $map to get an array of weights based on specified userId and then you can use $max to get final weight
db.col.aggregate([
$match: 'event._id':ObjectId('5c942a3591deb389bfd92579'), 'chats.enabled': $exists: true,
"$project":
"_id": 1,
"chats.user._id": 1,
"weight":
$max: $map: input: "$chats", in: $cond: [ $eq: [ "$$this.user._id", ObjectId("5c942a3591deb389bfd92579") ] , 10, 0 ]
,
"$sort": "weight": -1 ,
])
The problem here is that using $unwind you modify initial structure of your documents (you will get one document per chats
. I would suggest using $map to get an array of weights based on specified userId and then you can use $max to get final weight
db.col.aggregate([
$match: 'event._id':ObjectId('5c942a3591deb389bfd92579'), 'chats.enabled': $exists: true,
"$project":
"_id": 1,
"chats.user._id": 1,
"weight":
$max: $map: input: "$chats", in: $cond: [ $eq: [ "$$this.user._id", ObjectId("5c942a3591deb389bfd92579") ] , 10, 0 ]
,
"$sort": "weight": -1 ,
])
answered Mar 27 at 16:47
micklmickl
20.3k6 gold badges20 silver badges42 bronze badges
20.3k6 gold badges20 silver badges42 bronze badges
could you add an example if there was a list users instead of one object user? Like if it was a chats array and nested users array and then some ID
– Jonathan
Mar 27 at 17:02
1
@Jonathan you need double$map
and$max
then. Please give it a try and open another question if you still need some assistance, I will try to take a look later
– mickl
Mar 27 at 17:06
add a comment |
could you add an example if there was a list users instead of one object user? Like if it was a chats array and nested users array and then some ID
– Jonathan
Mar 27 at 17:02
1
@Jonathan you need double$map
and$max
then. Please give it a try and open another question if you still need some assistance, I will try to take a look later
– mickl
Mar 27 at 17:06
could you add an example if there was a list users instead of one object user? Like if it was a chats array and nested users array and then some ID
– Jonathan
Mar 27 at 17:02
could you add an example if there was a list users instead of one object user? Like if it was a chats array and nested users array and then some ID
– Jonathan
Mar 27 at 17:02
1
1
@Jonathan you need double
$map
and $max
then. Please give it a try and open another question if you still need some assistance, I will try to take a look later– mickl
Mar 27 at 17:06
@Jonathan you need double
$map
and $max
then. Please give it a try and open another question if you still need some assistance, I will try to take a look later– mickl
Mar 27 at 17:06
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55382336%2fsort-by-deep-document-field-in-mongodb%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
Could you show sample document from your collection ?
– mickl
Mar 27 at 16:39
added two documents where the second one should come first @mickl
– Jonathan
Mar 27 at 16:43